Use a filter based on cookies to enable the user to log on from each access.

Source: Internet
Author: User

Use a filter based on cookies to enable the user to log on from each access.

Original statement: This article is my original work. It is not extracted from other places. For reprint, contact the blogger.

I believe you will encounter this on all major websites. When you log on, the next login-free/one-month login-free option will appear in the login box. This blog post will explain how to implement it. Record it here, this is also a collection of memos. If there are any mistakes in the text, you are welcome to point out

Why do you log on once? Because when you access a page, if the first automatic logon fails, you will go through the automatic logon process again the next time you refresh the page, an endless loop will occur.

The sample code framework of this blog post is Spring MVC. The following describes the knowledge required to implement this function:Cookies and filters

1. cookies

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

Let's take a look at how to save and delete cookies.

  • Save cookies
String newUserName = null; try {newUserName = URLEncoder. encode (username, "UTF-8"); // transcode the user name to prevent the user name from being Chinese. The cookies are saved in Chinese and garbled.} catch (UnsupportedEncodingException e) {e. printStackTrace ();} Cookie nameCookie = new Cookie ("username", newUserName); String pwdMd5Cook = MD5Util. MD5 (Pwd); Cookie pwdCookie = new Cookie ("pwd", pwdMd5Cook); // Save the encrypted nameCookie. setMaxAge (60*60*24*365); // the user name is used to save pwdCookie for one year. setMaxAge (60*60*24*30); // Save the password for 30 days // send the Cookie information to the browser response. addCookie (nameCookie); response. addCookie (pwdCookie );

Deleting cookies is simple, but it is worthNote:Delete cookies.Same control layerOtherwise, the stored cookies cannot be found, resulting in deletion failure.

Cookie cookie = new Cookie ("pwd", null); cookie. setMaxAge (0); // Delete the password cookieresponse. addCookie (cookie );
2. Filter-Filter

Filter is also called a Filter. It is the most practical technology in Servlet technology. Web developers use the Filter technology to manage all web resources on web servers, such as Jsp, Servlet, static image files or static html files are intercepted to implement some special functions. For example, some advanced functions such as URL-level access control, filtering sensitive words, and compressing response information are implemented.

Implementation Method: Inherit the Filter interface and implement its doFilter method. Register the written filter class in the web. xml file and set the resources it can intercept.

<Filter> specify a filter. <Filter-name> specifies a name for the filter. The content of this element cannot be blank. The <filter-class> element is used to specify the full qualified class name of the filter. The <init-param> element is used to specify initialization parameters for the filter. Its sub-element <param-name> specifies the parameter name and <param-value> specifies the parameter value. In the filter, you can use the FilterConfig interface object to access initialization parameters. The <filter-mapping> element is used to set the resources intercepted by a Filter. You can specify the Servlet name and the Resource Access Request Path <Filter-name> sub-element in two ways for a filter to intercept the resource. The value must be the name of the filter declared in the <filter> element <url-pattern> to set the Request Path intercepted by the filter (the URL style associated with the filter) <servlet-name> specify the name of the Servlet intercepted by the filter. <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>

The actual application code is as follows:

Public class implements Filter {@ Overridepublic void destroy () {}@ Overridepublic void doFilter (ServletRequest request, response, FilterChain chain) throws IOException, response {HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req. getSession (); String requestURI = req. getRequestURI (); Str Ing 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 static resource chains such as css, js, and images. doFilter (request, response);} else if (requestURI. contains ("/info/") | requestURI. contains ("/gys/") {// filter the front-end access page, and automatically log on to the front-end personal Center (supplier background). If logon fails, no operation is performed, if the logon to the personal center is unsuccessful, go to the logon page and choose ProviderInfo providerInfo = (ProviderInfo) session. getAttribute ("providerInfo_gys"); String IsAutomaticLogin = (String) session. getAttribute ("IsAutomaticLogin"); // whether the automatic logon process has passed. if (requestURI. contains ("/info /")&&! RequestURI. contains ("/login") {// you do not need to log on to the portal (except for Logon). Log On only once. If the logon fails, 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/") {// you can log on to the personal center once. if (providerInfo = null & IsAutomaticLogin = 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 {// The chain is not filtered. doFilter (request, response) ;}@overridepublic void init (FilterConfig arg0) throws ServletException {}}

It can be seen from the code that a user needs to identify whether the user has logged on automatically (IsAutomaticLogin), Which is saved when you log on automatically (no matter whether it is unsuccessful ).

3. Based on the knowledge provided above, the overall code is shown below. If you find any problem, please point it out.
@ Controller @ RequestMapping ("/common ") public class CommonController {/*** Automatic Logon Method * @ param request * @ param response * @ param username * @ param pwd * @ param ProviderInfo model * @ return */ @ RequestMapping ("/automaticLogin ") public String automaticLogin (HttpServletRequest request, ServletResponse response, @ CookieValue (value = "username", required = false) String username, @ CookieValue (value = "pwd", Required = false) String pwd, ProviderInfo) {// Save the link String goURL = (String) session before login. getAttribute ("goURL"); if (username = null) {// There is no user name in cookies. You certainly do not need to log on to the session automatically. setAttribute ("IsAutomaticLogin", "0"); return "redirect:" + goURL;} else {try {username = URLDecoder. decode (username, "UTF-8"); // escape to prevent Chinese} catch (UnsupportedEncodingException e) {e. printStackTrace () ;}// session with cookie failure It must be blank because the user name will be saved in the cookie if ("". equals (username) | username = null) {// the user cannot log on using the session. No operation is performed. The user does not enter this method session. setAttribute ("IsAutomaticLogin", "0"); return "redirect:" + goURL;} No Password in else {// cookie. The session is determined not to be empty. If it is null, it indicates that no logon is performed. if it is not null, the user selects not to remember the password for Logon (so there is no password in the cookie) if ("". equals (pwd) | pwd = null) {ProviderInfo customer1 = (ProviderInfo) session. getAttribute ("providerInfo_gys"); if (customer1 = n Ull) {// you cannot log on using the session. You do not perform any operations or enter this method session. setAttribute ("IsAutomaticLogin", "0"); return "redirect:" + goURL;} else {// logged on, no longer entering this method return "redirect: "+ goURL ;}} else {// a password exists in the cookie. The session is determined not to be empty. If it is null, it indicates that no logon is performed. If it is not empty, indicates that you have logged on to the ProviderInfo customer1 = (ProviderInfo) session. getAttribute ("providerInfo_gys"); if (customer1 = null) {// the user name and password in cookies are called to log on. // automatic logon is performed, after successful logon, return to the original page ProviderInfo cust Omer3 = ValidateDate (username); customer3.setPwd (pwd); customer3.setAccountType (6); ProviderInfo customer2 = infoService. login (customer3); // call the logon method if (customer2 = null) {// The Automatic Logon fails and the method session is no longer entered. setAttribute ("IsAutomaticLogin", "0"); return "redirect:" + goURL;} else {// The user information is successfully saved to sessionsession. setAttribute ("providerInfo_gys", customer2); return "redirect:" + goURL;} else {return "redirect:" + goURL; }}}/*** User Login * @ param request * @ param response * @ param cuz * @ return */@ RequestMapping ("/UserLogin ") @ ResponseBodypublic Map <String, Object> goLogin (HttpServletRequest request, HttpServletResponse response, @ ModelAttribute ("ProviderInfo") ProviderInfo cuz) {/* omitting some logical judgments */cuz. setPwd (MD5Util. MD5 (Pwd); ProviderInfo providerInfo = infoService. login (cus); Map <String, Cookie> cookieMap = new HashMap <Stri Ng, Cookie> (); if (providerInfo = null) {// Login Failed, jump to the login page again map. put ("error", "Password error"); return map;} else {String newUserName = null; if (remember_me.equals ("1 ")) {// if you have selected a month for login-free 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 = n Ew Cookie ("pwd", pwdMd5Cook); // Save the encrypted password + "create" nameCookie. setMaxAge (60*60*24*365); // the user name is used to save pwdCookie for one year. setMaxAge (60*60*24*30); // Save the password for 30 days // send the Cookie information to the browser response. addCookie (nameCookie); response. addCookie (pwdCookie); session. setAttribute ("IsAutomaticLogin", null);} else {// no selection, delete the password Cookie that may have been selected for Automatic Logon last time [] cookies = request. getCookies (); if (null! = Cookies) {for (Cookie cookie: cookies) {cookieMap. put (cookie. getName (), cookie) ;}} if (cookies! = Null) {for (int I = 0; I <cookies. length; I ++) {if (cookieMap. containsKey ("pwd") {Cookie cookie = new Cookie ("pwd", null); cookie. setMaxAge (0); // Delete the password cookieresponse. addCookie (cookie) ;}}}// login successful. Save the current user information and save the customer information to sessionmap. put ("ProviderInfo", providerInfo); map. put ("goURL", session. getAttribute ("goURL"); session. setAttribute ("providerInfo_gys", providerInfo); return map;} else {map. put ("error", "This Supplier 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 (cookies! = Null) {for (int I = 0; I <cookies. length; I ++) {if (cookieMap. containsKey ("pwd") {Cookie cookie = new Cookie ("pwd", null); cookie. setMaxAge (0); // Delete the password cookieresponse. addCookie (cookie) ;}} session. setAttribute ("providerInfo_gys", null); return "/index ";}}

At this point, all examples of this function have been completed. If anything is incorrect, you are welcome to point it out in the comment area.

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.