A detailed description of the client Access login function based on cookies using filters

Source: Internet
Author: User
This article mainly describes the use of filters based on cookies to enable customers to login only once per visit, the need for friends can refer to the next

I believe that everyone in the major sites will encounter, log in, the login box appears the next time free landing/One months of similar options to avoid landing, this article is to explain how to achieve, in this record, but also to do a memorandum collection, if the text is wrong, you are welcome to point out

Why do you say that since landing once, because when a page is visited, if the first automatic logon failure, you will be the next time you refresh the access to the automatic logon process, there would be a dead loop.

The code sample framework for this article is spring MVC, and the following explains what you need to know to implement this feature: Cookies and filters

1.cookies

What is cookies:cookies provides a useful way for WEB applications to save user-related information. For example, when a user accesses your site, you can use cookies to save user preferences or other information so that the application can retrieve previously saved information the next time the user accesses your site.

Let's look at how cookies are stored and how to delete cookies.

Save cookies


String Newusername = null;try {  newusername = Urlencoder.encode (username, "UTF-8");//transcoding the username to prevent the user name from being Chinese, Cookies save Chinese out will be garbled} catch (Unsupportedencodingexception e) {  e.printstacktrace ();} Cookie Namecookie = new Cookie ("username", newusername); String Pwdmd5cook = MD5UTIL.MD5 (PWD); Cookie Pwdcookie = new Cookie ("pwd", pwdmd5cook);//Save encrypted password Namecookie.setmaxage (60 * 60 * 24 * 365);//username for one year PWDCOOKIE.S Etmaxage (60 * 60 * 24 * 30);//Password Save 30 days//Send cookie information to browser Response.addcookie (Namecookie); Response.addcookie (Pwdcookie);

Delete cookies, delete very simple, but it is worth noting, delete cookies, and save cookies must be in the same control layer, otherwise will not find the saved cookies, resulting in deletion


Cookie cookie = new Cookie ("PWD", null); Cookie.setmaxage (0);//delete password Cookieresponse.addcookie (cookie);

2.filter-Filter

Filter, also known as filters, is the most practical technology in Servlet technology, Web developers through the filter technology, Web server management of all Web resources: such as JSP, Servlet, static picture files or static HTML files, etc. to intercept, So that some special functions can be realized. For example, the implementation of URL-level access control, filtering sensitive words, compressed response information and other advanced features.

Implementation method: Inherit the filter interface and implement its Dofilter method. Registers the Write filter class in the Web. xml file and sets the resources it can intercept


<filter> Specify a filter. <filter-name> is used to specify a name for the filter, and the content of the element cannot be empty. The <filter-class> element is used to specify the full qualified class name of the filter. The <init-param> element is used to specify the initialization parameters for the filter, its child elements <param-name> the name of the specified parameter,<param-value> the value of the specified parameter. In a filter, you can use the Filterconfig interface object to access the initialization parameters. The <filter-mapping> element is used to set a resource that the filter is responsible for intercepting. A filter interception resource can be specified in two ways: the request path to the Servlet name and the resource access <filter-name> child elements used to set the registration name of the filter. The value must be the name of the filter declared in the <filter> element <url-pattern> set the request path blocked by filter (the URL style associated with the filter) <servlet-name> Specifies the name of the servlet that the filter intercepts. <filter>  <filter-name>suicaiFilter</filter-name>  <filter-class> Com.suicai.filter.suicaifilter</filter-class></filter><filter-mapping>  <filter-name >suicaiFilter</filter-name>  <url-pattern>/*</url-pattern></filter-mapping>

Here's a look at the actual application code:


public class Suicaifilter implements Filter {@Override public void Destroy () {} @Override public void DoFilter (Serv Letrequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {httpservletreque    St Req= (httpservletrequest) request;    HttpServletResponse res= (httpservletresponse) response;    HttpSession session = Req.getsession ();    String RequestUri = Req.getrequesturi ();    String param = req.getquerystring ();    String URL = req.getservletpath (); if (param!=null) {url = url+ "?")    +param; } if (Requesturi.contains ("js") | | | requesturi.contains ("CSS") | | requesturi.contains ("images")) {//Do not filter css,js,images    such as static resource Chain.dofilter (request, response); }else if (requesturi.contains ("/info/") | | Requesturi.contains ("/gys/")) {//filter the Front desk access page, with the front desk personal Center (vendor backend), automatic login once, the login is unsuccessful, the personal center login is unsuccessful, then skip to the login page Providerinfo provid      Erinfo = (providerinfo) session.getattribute ("Providerinfo_gys"); String isautomaticlogin = (string) session.gEtattribute ("Isautomaticlogin");//has passed the automatic login process identity if (Requesturi.contains ("/info/") &&!requesturi.contains ("/login"))          {//Access portal, etc. do not need to login (except login), only try to log in once, if not successful, do not operate if (providerinfo==null && isautomaticlogin = = null) {          Req.getsession (). SetAttribute ("Gourl", url);        Res.sendredirect (Req.getcontextpath () + "/common/automaticlogin");        }else if (providerinfo==null && isautomaticlogin! = null) {Chain.dofilter (request, response);        }else{Chain.dofilter (request, response); }}else if (Requesturi.contains ("/gys/")) {//access to personal center, from login once, unsuccessful jump to login page if (providerinfo==null && Isautomati          Clogin = = null) {req.getsession (). SetAttribute ("Gourl", url);        Res.sendredirect (Req.getcontextpath () + "/common/automaticlogin");          }else if (providerinfo==null && isautomaticlogin! = null) {Session.setattribute ("RedirectURL", url); Res.sendredirect (Req.getcontextpath () + "/login.jsp?redirecturl=" +url);        }else{Chain.dofilter (request, response);      }}else{Chain.dofilter (request, response);    }}else{//Do not filter chain.dofilter (request, response); }} @Override public void init (Filterconfig arg0) throws servletexception {}}

As you can see from the code, you need an identity that has been automatically logged in (Isautomaticlogin), which is saved when you walk an automatic login (whether it's unsuccessful)

3. Combined with the above to provide knowledge, the following is the overall code display, if found wrong place, welcome to point out


@Controller @requestmapping ("/common") public class commoncontroller{/** * Automatic Login method * @param request * @param response * @param username * @param pwd * @param providerinfo vendor account Information Model * @return */@RequestMapping ("/automaticlogi n ") public String Automaticlogin (httpservletrequest request,servletresponse response, @CookieValue (value =" username ",    Required = False) string username, @CookieValue (value = "pwd", Required = False) string Pwd,providerinfo providerinfo) {    Save requirements before login link String gourl = (string) session.getattribute ("Gourl");      if (username = = null) {//cookies does not have a username, it certainly does not require automatic login Session.setattribute ("Isautomaticlogin", "0");    Return "Redirect:" + Gourl; } else {try {username = Urldecoder.decode (username, "UTF-8");//Escape, prevent Chinese} catch (Unsupportedencodingexce      Ption e) {e.printstacktrace (); }}//Cookie expiration session must be empty, because when logged in, the user name must be saved in the cookie if ("". Equals (username) | | Username = = NULL) {//Use session login not, no action, no entryThis method Session.setattribute ("Isautomaticlogin", "0");    Return "Redirect:" + Gourl; } else {//The cookie does not have a password, the session is not empty, if it is empty, the description is not logged in, if not empty, the user is chosen not to remember the password login (so the cookie does not have a password) if ("". Equals (pwd) | |        PWD = = null) {Providerinfo customer1 = (providerinfo) session.getattribute ("Providerinfo_gys");          if (customer1 = = null) {//Use session login not, do not take any action, do not enter this method Session.setattribute ("Isautomaticlogin", "0");        Return "Redirect:" + Gourl;        } else {//already logged in, no longer entering this method return "Redirect:" + Gourl;  }} else {//cookie has a password to determine if the session is not empty, if it is empty, the description is not logged in, if not empty, the description is already logged in Providerinfo Customer1 = (providerinfo)        Session.getattribute ("Providerinfo_gys");  if (customer1 = = null) {//not currently logged in, call the username and password in the cookie to log in/do an automatic login operation, log in successfully and return to the original page Providerinfo Customer3 =          Validatedate (username);          Customer3.setpwd (PWD);          Customer3.setaccounttype (6); Providerinfo Customer2 = Infoservice.login(customer3);//Call the login method if (Customer2 = = null) {//automatic login failed, no longer enter this method Session.setattribute ("Isautomaticlogin            "," 0 ");          Return "Redirect:" + Gourl;            } else {//login successfully saved customer information to session Session.setattribute ("Providerinfo_gys", customer2);          Return "Redirect:" + Gourl;        }} else {return "redirect:" + Gourl; }}}}/** * User login * @param request * @param response * @param cus * @return * * * @RequestMapping ("/u Serlogin ") @ResponseBody public map<string, object> gologin (HttpServletRequest request,httpservletresponse    Response, @ModelAttribute ("Providerinfo") Providerinfo cus) {/* Omit some logic judgments */CUS.SETPWD (MD5UTIL.MD5 (PWD));    Providerinfo providerinfo = Infoservice.login (cus);    map<string, cookie> cookiemap = new hashmap<string, cookie> ();      if (Providerinfo = = null) {//Login failed, re-jump to landing page map.put ("Error", "Password Wrong");    return map; }else{String NEWusername = null;        if (Remember_me.equals ("1")) {//have selected one months free login try {newusername = Urlencoder.encode (username, "UTF-8");        } catch (Unsupportedencodingexception e) {e.printstacktrace ();        } Cookie Namecookie = new Cookie ("username", newusername);        String Pwdmd5cook = MD5UTIL.MD5 (PWD); Cookie Pwdcookie = new Cookie ("pwd", pwdmd5cook),//Save encrypted password + "create" namecookie.setmaxage (60 * 60 * 24 * 365); The username is saved for one year pwdcookie.setmaxage (60 * 60 * 24 * 30);//Password Save 30 days//Send cookie information to browser Response.addcookie (Namecoo        Kie);        Response.addcookie (Pwdcookie);      Session.setattribute ("Isautomaticlogin", null);        }else{//no option to delete the last password that may have been selected for automatic login cookie[] cookies = request.getcookies ();          if (null! = cookies) {for (Cookie cookie:cookies) {cookiemap.put (Cookie.getname (), cookie); }} if (cookie = null) {for (int i = 0; i < cookies.length; i++) {           if (Cookiemap.containskey ("pwd")) {Cookie cookie = new Cookie ("PWD", null);            Cookie.setmaxage (0);//delete password cookie Response.addcookie (cookie);      }}}}//Login successful, save current user information, save customer information to session map.put ("Providerinfo", providerinfo);      Map.put ("Gourl", Session.getattribute ("Gourl"));      Session.setattribute ("Providerinfo_gys", providerinfo);    return map;      }else {map.put ("error", "The vendor account does not exist");    return map; }}/** * Logout * @return * * * @RequestMapping ("/logout") public String Logout (httpservletresponse response) {Map    <string, cookie> cookiemap = new hashmap<string, cookie> ();    cookie[] cookies = request.getcookies ();      if (null! = cookies) {for (Cookie cookie:cookies) {cookiemap.put (Cookie.getname (), cookie); }} if (cookie = null) {for (int i = 0; i < cookies.length; i++) {if (Cookiemap.containskey ("pwd"         )) { Cookie cookie = new Cookie ("PWD", null);        Cookie.setmaxage (0);//delete password cookie Response.addcookie (cookie);    }}} session.setattribute ("Providerinfo_gys", null);  return "/index"; }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.