Cookie-based filters enable users to log on only once each access. cookie Filters

Source: Internet
Author: User

Cookie-based filters enable users to log on only once each access. cookie Filters

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 article will explain how to implement it and 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 framework of this Code 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 );

It is very easy to delete cookies, but it is worth noting that the deletion of cookies must be at the same control layer as the preservation of cookies. Otherwise, the stored cookies cannot be found and cannot be deleted.

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 suicaiFilter implements Filter {@ Override public void destroy () {}@ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, servletException {HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req. getSession (); String requestURI = req. getRequest URI (); 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 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 IsAutomaticL Ogin = (String) session. getAttribute ("IsAutomaticLogin"); // whether the automatic logon process ID 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) ;}@override public void init (FilterConfig arg0) throws ServletException {}}

It can be seen from the code that an ID (IsAutomaticLogin) that has been automatically logged on is required. This ID 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 = "p Wd ", 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 ();}}// The cookie invalidation session 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_g Ys "); if (customer1 = null) {// the user cannot log on using the session. No operation is performed and the user does not 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. After Successful Logon, the system returns the original page ProviderInfo customer3 = ValidateDate (username), customer3.setPwd (pwd), customer3.setAccountType (6), and 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 client information is successfully saved to the session. setAttribute ("providerInfo_gys", customer2); return "redirect: "+ GoURL ;}}else {return" redirect: "+ goURL ;}}}} /*** log on to the user * @ param request * @ param response * @ param cuz * @ return */@ RequestMapping ("/UserLogin") @ ResponseBody public Map <String, object> goLogin (HttpServletRequest request, HttpServletResponse response, @ ModelAttribute ("ProviderInfo") ProviderInfo cus) {/* omitting some logical judgments */cus. setPwd (MD5Util. MD5 (Pwd); ProviderInfo providerInfo = infoService. Login (cus); Map <String, Cookie> cookieMap = new HashMap <String, Cookie> (); if (providerInfo = null) {// login failed, jump back to the login page 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 ("usernam E ", newUserName); String pwdMd5Cook = MD5Util. MD5 (Pwd); Cookie pwdCookie = new 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 [] coo Kies = 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 cookie response. addCookie (cookie) ;}}}// login successful. Save the current user information and save the customer information to the session map. 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 ;}/ *** deregister * @ 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 cookie response. addCookie (cookie) ;}} session. setAttribute ("providerInfo_gys", null); return "/index ";}}

The above section describes how to use a filter based on cookies to enable users to log on only once for each access. I hope this will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.