Web Filters (Jsp+cookie+filter-free tomcat) use records __JS

Source: Internet
Author: User

Note: The filter mainly filters the value inside the request,response.

*web.xml----

* Login Action Add cookie-------

*filter Filter Gets cookies------

(without a new username, password, read the cookie directly through the query database, get user user,

Request.getsession (). setattribute ("user", User1))

* Other action inside get---------

(Duser user= (Duser) request.getsession (). getattribute ("user"),//) Automatic logon

* Logoff: Deleting cookies----------

1, Web configuration file--Filter all requests

<filter>
  <filter-name>LoginFilter</filter-name>
  <filter-class> com.djh.listener.loginfilter</filter-class>
 </filter>
 <filter-mapping>
  < filter-name>loginfilter</filter-name>
  <url-pattern>/*</url-pattern>
 </ Filter-mapping>

2. Add Cookies to login action

Session.setattribute ("user", user);
      Cookie cookie1 = new Cookie ("username", User.getuphonenum ());  
               Cookie cookie2 = new Cookie ("Password", User.getupassword ());               Cookie cookie3 = new Cookie ("SESSIONID", "----");
               
               Cookie1.setmaxage (*);  
               Cookie2.setmaxage (*);               cookie3.setmaxage (0); 
               
               
               Cookie1.setpath ("/");  
               Cookie2.setpath ("/");               Cookie3.setpath ("/");  
                 
               Response.addcookie (cookie1);  
               Response.addcookie (COOKIE2);  


3, Filter class loginfilter--Main method is Dofilter, in this method to remove request.getccookies () value, set to Request.getsession (). setattribute ("User", User1);
, the other interface takes the "user" value from the filter set to remove the Uname,password automatic login.

Package Com.djh.listener;

Import java.io.IOException;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;

Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Com.djh.entity.DUser;
Import Com.djh.service.LoginService;

Import com.djh.util.MD5; /** * @author Shenpai * Filter for automatic user login/public class Loginfilter implements filter {ApplicationContext context = new 
 Classpathxmlapplicationcontext (New string[]{"Applicationcontext-*.xml"}); Loginservice loginservice= (Loginservice) Context.getbean ("Loginservice");//Get UserService instance of the bean with public void Destroy () {} public void Dofilter (ServletRequest req, servletresPonse resp, Filterchain chain) throws IOException, Servletexception {try {//System.out.println ("------------
   ----"); Convert ServletRequest and Servletresponse to HttpServletRequest and HttpServletResponse types HttpServletRequest request= (
   HttpServletRequest) req;
   HttpServletResponse response = (httpservletresponse) resp; First check that the user is logged on to Duser user= (duser) request.getsession (). getattribute ("user");/if (user!=null) {Chain.dofilter (req
    Uest, response);
   Return
   //Check to see if the user brought a cookie String username= null;
   String password =null;
   Cookie[] Cookies=request.getcookies (); for (int i=0;cookies!=null && i<cookies.length;i++) {//System.out.println (Cookies[i].getname () +cookies[i
             ].getvalue () + "----filter to obtain cookies---");  
             if (Cookies[i].getname (). Equals ("username")) {username = Cookies[i].getvalue (); } if (Cookies[i].getname (). Equals ("password")) {password = Cookies[i].getvalue();  
              } if (Username==null | | password==null) {//user did not bring Cookie Chain.dofilter (req, resp);  
         Return  
         }//The user brought the cookie duser user1 = Loginservice.finduserbyphonenumandpassword (username, password);  
         String Save_password = User1.getupassword ();  
             if (!password.equals (Save_password)) {Chain.dofilter (req, resp);  
         Return  } request.getsession (). setattribute ("user", User1);
         Through the requsest to the relevant need to login information in the action, the action inside through the reqest. Obtain user information and implement automatic login.
         Chain.dofilter (req, resp); 
  Return
  catch (Exception e) {e.printstacktrace ();




 } public void init (Filterconfig arg0) throws servletexception {}}


4, action to obtain user information, to achieve automatic login.

Duser user= (Duser) session.getattribute ("user");//Get the Login user Object

5. Logout: Delete Cookies

User logoff public
 String logout () {
            HttpSession session = Request.getsession (false);
            if (session!= null)
            session.removeattribute ("user");
            Cookie cookie = Cookieutils.<span style= "Background-color: #3333ff" >delCookie</span> (request);
            if (cookie!= null)
                    Response.addcookie (cookie);
            return "Login";
 


Private Cookieutils cookieutils = new Cookieutils ();

Delete Cookie public
 cookie <span style= "color: #3333ff;" >delCookie</span> (HttpServletRequest request) {
         cookie[] cookies = request.getcookies ();
         if (cookies!= null) {for
                  (Cookie cookie:cookies) {
                         if ("username". Equals (Cookie.getname ())) {
                                Cookie.setv Alue ("");
                                Cookie.setmaxage (0);
                          } else if ("Password". Equals (Cookie.getname ())) {
                                cookie.setvalue ("");
                                Cookie.setmaxage (0);
                         }
                         return cookie;
                 }
         return null;
 }


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.