Common Application of filter filter in Javaweb _java

Source: Internet
Author: User
Tags html form md5 md5 encryption browser cache

One, unified whole station character code

Use the configuration parameter charset to indicate what character encoding is used to handle the Chinese issue of HTML form request parameters

Package me.gacl.web.filter;
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.HttpServletRequest;
Import Javax.servlet.http.HttpServletRequestWrapper;

Import Javax.servlet.http.HttpServletResponse; /** * @ClassName: Characterencodingfilter * @Description: This filter is used to solve the whole station Chinese garbled problem * * public class Characterencodingfilter Implem
  Ents Filter {private filterconfig filterconfig = null;

  Set the default character encoding private String Defaultcharset = "UTF-8"; public void Dofilter (ServletRequest req, Servletresponse resp, Filterchain chain) throws IOException, Servletexcepti
    on {httpservletrequest request = (httpservletrequest) req;
    HttpServletResponse response = (httpservletresponse) resp;
    String charset = Filterconfig.getinitparameter ("charset");
  if (charset==null) {    charset = Defaultcharset;
    } request.setcharacterencoding (CharSet);
    Response.setcharacterencoding (CharSet);
    
    Response.setcontenttype ("text/html;charset=" +charset);
    Mycharacterencodingrequest requestwrapper = new Mycharacterencodingrequest (request);
  Chain.dofilter (requestwrapper, response); } public void init (Filterconfig filterconfig) throws Servletexception {//Get the initialization configuration information for the filter this.filterconfig = fil
  Terconfig; public void Destroy () {}}/* 1. Implement the same interface 2 as the enhanced object, define a variable remember to be enhanced Object 3, define a constructor, receive the enhanced object 4, overwrite the need to enhance the method 5, for the method that does not want to enhance, direct call is Methods to enhance objects (target objects) * * Class Mycharacterencodingrequest extends httpservletrequestwrapper{private httpservletrequest re
  Quest
    Public mycharacterencodingrequest (HttpServletRequest request) {super (request);
  This.request = Request; /* Rewrite GetParameter method * @see Javax.servlet.servletrequestwrapper#getparameter (java.lang.String) */@Override P Ublic string GetParameter (string name) {TRy{//Gets the value of the parameter String value= this.request.getParameter (name);
      if (value==null) {return null;
      ///If the data is not submitted in a get way, returns the obtained value if (!this.request.getmethod (). Equalsignorecase ("gets")) {return value; }else{//If the data is submitted in a get way, the value obtained is transcoding (value.getbytes) = new String ("Iso8859-1"), This.request.get
        Characterencoding ());
      return value;
    }}catch (Exception e) {throw new RuntimeException (e);

 }
  }
}

The configuration in the Web.xml file is as follows:

<filter>
   <filter-name>CharacterEncodingFilter</filter-name>
   <filter-class> me.gacl.web.filter.characterencodingfilter</filter-class>
   <init-param>
     <param-name> charset</param-name>
     <param-value>UTF-8</param-value>
   </init-param>
 </ filter>
 
 <filter-mapping>
   <filter-name>CharacterEncodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

Second, prohibit browser cache all dynamic pages
there are 3 HTTP response header fields that can prevent browsers from caching the current page, and their example code in the Servlet is as follows:

    • Response.setdateheader ("Expires",-1);
    • Response.setheader ("Cache-control", "No-cache");
    • Response.setheader ("Pragma", "No-cache");

Not all browsers fully support the top three response headers, so it is best to use the top three response headers at the same time.

    • Expires Data header: Value is GMT time value, 1 refers to browser do not cache page
    • The Cache-control response header has two common values:
    • No-cache refers to browsers not to cache the current page.
    • Max-age:xxx refers to the browser caching page xxx seconds.

Package me.gacl.web.filter;

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.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; /** * @ClassName: Nocachefilter * @Description: Prevent browser from caching all dynamic pages * @author: Aloof Wolf * @date: 2014-8-31 Afternoon 11:25:40 * * * * public C Lass Nocachefilter implements Filter {public void Dofilter (ServletRequest req, Servletresponse resp, Filterchai N chain) throws IOException, Servletexception {//Turn ServletRequest into HttpServletRequest httpservletrequest request
    = (httpservletrequest) req;
    Turn the servletresponse into httpservletresponse httpservletresponse response = (httpservletresponse) resp;
    Prevents browsers from caching all dynamic page Response.setdateheader ("Expires",-1);
    Response.setheader ("Cache-control", "No-cache"); Response.sethEader ("Pragma", "No-cache");
  Chain.dofilter (request, response);

 } public void init (Filterconfig filterconfig) throws servletexception {} public void Destroy () {}}

The configuration in the Web.xml file is as follows:

<filter>
   <filter-name>NoCacheFilter</filter-name>
   <filter-class> me.gacl.web.filter.nocachefilter</filter-class>
 </filter>
 
 <filter-mapping>
   < Filter-name>nocachefilter</filter-name>
    <!--only intercept JSP requests-->
   <servlet-name>*.jsp</ Servlet-name>
 </filter-mapping>

Control the static resources in the browser cache page

Some dynamic pages refer to some pictures or CSS files to decorate the page effect, these pictures and CSS files are often unchanged, so in order to reduce the pressure on the server, you can use the filter to control the browser cache these files to improve the performance of the server.

Package me.gacl.web.filter;

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.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; /** * @ClassName: Cachefilter * @Description: Control Cache Filter */public class Cachefilter implements filter {private Filt

  Erconfig Filterconfig; public void Dofilter (ServletRequest req, Servletresponse resp, Filterchain chain) throws IOException, Servletexcepti
    on {httpservletrequest request = (httpservletrequest) req;
    
    HttpServletResponse response = (httpservletresponse) resp; 
    
    1. Get the resources the user wants to access String URI = Request.getrequesturi (); 2. The suffix name String ext = uri.substring (Uri.lastindexof (".") of the resource to which the user wants to access.
    
    +1);
    Get the resource need to cache time String = filterconfig.getinitparameter (EXT); IfTime!=null) {Long T = Long.parselong (time) *3600*1000;
    Set Cache Response.setdateheader ("Expires", System.currenttimemillis () + t);

  Chain.dofilter (request, response);
  public void init (Filterconfig filterconfig) throws servletexception {this.filterconfig = Filterconfig;

 public void Destroy () {}}

The configuration in the

Web.xml file is as follows:

<!--Configure Cache filters--> <filter> <filter-name>CacheFilter</filter-name> <filter-class>me.g Acl.web.filter.cachefilter</filter-class> <!--Configure the Web resources to cache and the cache time, in hours--> <init-param> ;p aram-name>css</param-name> <param-value>4</param-value> </init-param> <init-par
   am> <param-name>jpg</param-name> <param-value>1</param-value> </init-param> <init-param> <param-name>js</param-name> <param-value>4</param-value> </i nit-param> <init-param> <param-name>png</param-name> <param-value>4</param-valu E> </init-param> </filter> <!--Configure the suffix of the Web resource to cache--> <filter-mapping> <filter-name> Cachefilter</filter-name> <url-pattern>*.jpg</url-pattern> </filter-mapping> < Filter-mapping> <filter-nAme>cachefilter</filter-name> <url-pattern>*.css</url-pattern> </filter-mapping> < Filter-mapping> <filter-name>CacheFilter</filter-name> <url-pattern>*.js</url-pattern > </filter-mapping> <filter-mapping> <filter-name>CacheFilter</filter-name> <url-pa
 Ttern>*.png</url-pattern> </filter-mapping>

Four, the realization user automatic landing

The idea is this:

1, after the user login successfully, send a cookie called user to the client, the value of the cookie is the username and MD5 encrypted password.
2. Write a autologinfilter, this filter checks whether the user has a cookie with the name of user, and if so, whether the user name and password of the DAO query cookie are matched to the database. A match is stored in the session with the user object (that is, the login flag) to achieve automatic landing of the program.

The core code is as follows:

Controller to process user login: Loginservlet

Package Me.gacl.web.controller;

Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Me.gacl.dao.UserDao;
Import Me.gacl.domain.User;

Import Me.gacl.util.WebUtils; public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respo
    NSE) throws Servletexception, IOException {String username = request.getparameter ("username");
    
    String Password = request.getparameter ("password");
    Userdao dao = new Userdao ();
    User user = Dao.find (username, password); if (user==null) {request.setattribute ("message"), "username or password is wrong!!
      ");
      Request.getrequestdispatcher ("/message.jsp"). Forward (request, response);
    Return
    } request.getsession (). setattribute ("user", user); Send an automatic login cookie to the client browser for storage SendautologincooKie (Request,response,user);
  Request.getrequestdispatcher ("/index.jsp"). Forward (request, response);  /** * @Method: Sendautologincookie * @Description: Send automatic login cookie to client browser * @param request * @param response *  @param user */private void Sendautologincookie (HttpServletRequest request, httpservletresponse response, user user) {if (Request.getparameter ("Logintime")!=null) {int logintime = Integer.parseint (Request.getparameter ("Loginti
      Me ")); The name of the creation Cookie,cookie is Autologin, the value is the username and password that the user logs on, and the username and password are used between the user. To split, password through MD5 encryption processing Cookie cookie = new Cookie ("Autologin", use
      R.getusername () + "." + WEBUTILS.MD5 (User.getpassword ());
      Set the validity period of the cookie Cookie.setmaxage (logintime);
      Set a valid path for the cookie Cookie.setpath (Request.getcontextpath ());
    Writes a cookie to the client browser Response.addcookie (cookie); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOE xception {doget (reqUest, response);

 }

}

Filter for handling user automatic logons: autologinfilter

Package me.gacl.web.filter;

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 Me.gacl.dao.UserDao;
Import Me.gacl.domain.User;

Import Me.gacl.util.WebUtils; public class Autologinfilter implements Filter {public void Dofilter (ServletRequest req, Servletresponse resp, F
    Ilterchain chain) throws IOException, servletexception {httpservletrequest request = (httpservletrequest) req;
    HttpServletResponse response = (httpservletresponse) resp; If you are already logged in, direct chain.dofilter (request, response) to release if (Request.getsession (). getattribute ("user")!=null) {Chain.dofi
      Lter (request, response);
    Return //1. Get the Authlogin cookie that the user brought over
    String value = null;
    Cookie cookies[] = request.getcookies ();
        for (int i=0;cookies!=null && i<cookies.length;i++) {if (Cookies[i].getname (). Equals ("Autologin")) {
      Value = Cookies[i].getvalue (); }//2. Get username and password in cookie if (value!=null) {String username = value.split ("\.")
      [0]; String Password = value.split ("\.")
      
      [1];
      3. Invoke DAO to obtain the user's corresponding password Userdao DAO = new Userdao ();
      User user = Dao.find (username);
      
      String Dbpassword = User.getpassword (); 4. Check the MD5 password that the user brought over and the password in the database to match, if the match automatically log in if (Password.equals (WEBUTILS.MD5 (Dbpassword))) {request.getsession ().
      SetAttribute ("user", user);
  } chain.dofilter (request, response);

 public void Destroy () {} public void init (Filterconfig filterconfig) throws servletexception {}}

If you want to cancel automatic logon, you can delete the automatic logon cookie when the user logs off, with the core code:

Package Me.gacl.web.controller;

Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; public class Cancelautologinservlet extends HttpServlet {public void doget (HttpServletRequest request, HTTPSERVLETRESP Onse response) throws Servletexception, IOException {//Remove user request.getsession () stored in session. Removeattrib
    Ute ("user");
    Remove the automatic login cookie Removeautologincookie (request,response);
  Log off the user and jump to the login page request.getrequestdispatcher ("/login.jsp"). Forward (request, response); /** * @Method: Removeautologincookie * @Description: Delete the automatic login cookie, * The way to delete cookies in Javaweb is to create a new cookie, the newly created Cooki E has the same name as the cookie to be deleted, * setting the lifetime of the cookie for the newly created cookie is set to 0, and the valid path is the same as the valid path of the cookie to be deleted * @param request * @param response * * PRIV ate void Removeautologincookie (HttpServletRequest request, HttpservleTresponse response) {//Create a cookie cookie with name autologin = new Cookie ("Autologin", "");
    Set the lifetime of the cookie to 0, and command the browser to delete the cookie cookie.setmaxage (0);
    Set the path Cookie.setpath (Request.getcontextpath ()) of the cookie to be deleted;
  Response.addcookie (cookie); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep
  tion {doget (request, response);

 }
}

Above is the filter of several common application scenarios, I hope to help you learn.

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.