Javaweb Learning Summary (46)--filter (filter) Common applications

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

Javaweb Learning Summary (46)--filter (filter) Common application One, unified all-station character encoding

Specify which character encoding to use to handle the Chinese problem of the HTML form request parameter by configuring the parameter charset

 1 package me.gacl.web.filter; 2 3 Import java.io.IOException; 4 Import Javax.servlet.Filter; 5 Import Javax.servlet.FilterChain; 6 Import Javax.servlet.FilterConfig; 7 Import javax.servlet.ServletException; 8 Import Javax.servlet.ServletRequest; 9 Import javax.servlet.servletresponse;10 Import javax.servlet.http.httpservletrequest;11 Import JAVAX.SERVLET.HTTP.HTTPSERVLETREQUESTWRAPPER;12 Import javax.servlet.http.httpservletresponse;13 14/**15 * @  CLASSNAME:CHARACTERENCODINGFILTER16 * @Description: This filter to solve the whole station Chinese garbled problem * @author: Aloof Wolf * @date: 2014-8-31 pm 11:09:3719     *20 * * Public class Characterencodingfilter implements Filter {Filterconfig filterconfig = null;24 Sets the default character encoding of the private String Defaultcharset = "UTF-8"; n-public void DoFilter (ServletRequest req, servletres Ponse resp,28 Filterchain chain) throws IOException, servletexception {httpservletreques T request = (httpservletrequest) req;31 HttpServletResponse Response = (httpservletresponse) resp;32 String charset = Filterconfig.getinitparameter ("charset"); 33 if (charset==null) {charset = defaultcharset;35}36 request.setcharacterencoding (CharSet         ), PNs response.setcharacterencoding (CharSet), Response.setcontenttype ("text/html;charset=" +charset); 39 Mycharacterencodingrequest requestwrapper = new Mycharacterencodingrequest (request); Chain.dofi         Lter (requestwrapper, response);}43. public void init (Filterconfig filterconfig) throws Servletexception {45 Get the initialization configuration information for the filter this.filterconfig = filterconfig;47}48-public void Destroy () {50 51} 52}53 54/*55 1. Implement the same interface as the enhanced Object 56 2, define a variable remember the enhanced Object 57 3, define a constructor, receive the enhanced Object 58 4, overwrite the method that needs to be enhanced 59 5, for methods that do not want to be enhanced, call the enhanced object directly (target object) method 60 * /61-Class Mycharacterencodingrequest extends httpservletrequestwrapper{63-Private httpservletrequest reques T;65 Public MycharactErencodingrequest (HttpServletRequest request) {n ' (request); this.request = request;68}69 /* Rewrite GetParameter method * @see javax.servlet.servletrequestwrapper#getparameter (java.lang.String) */72 @Over  Ride73 public string GetParameter (string name) {try{76//Gets the value of the parameter of the string             Value= This.request.getParameter (name); if (value==null) {return null;80}81                 If the data is not submitted in a get way, it is returned directly to the obtained value of the!this.request.getmethod (). Equalsignorecase ("get") {83 return value;84}else{85//If the data is submitted in a Get mode, the obtained value will be transcoded with the values = new St         Ring (Value.getbytes ("Iso8859-1"), this.request.getCharacterEncoding ()); return value;88}89 }catch (Exception e) {new runtimeexception (e); 91}92}93}

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

1  <filter> 2       <filter-name>CharacterEncodingFilter</filter-name> 3       <filter-class >me.gacl.web.filter.CharacterEncodingFilter</filter-class> 4       <init-param> 5           < Param-name>charset</param-name> 6           <param-value>UTF-8</param-value> 7       </ Init-param> 8   </filter> 9   <filter-mapping>11       <filter-name> characterencodingfilter</filter-name>12       <url-pattern>/*</url-pattern>13   </ Filter-mapping>
Second, prohibit browser cache all dynamic pages

There are 3 HTTP response header fields that can prevent the browser from caching the current page, and their sample code in the Servlet is as follows:

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

    • Expires Data header: Value GMT time value, 1 refers to the browser do not cache the page
    • The Cache-control response header has two common values:
    • No-cache refers to the browser does not cache the current page.
    • Max-age:xxx refers to the browser cache page xxx seconds.
 1 package me.gacl.web.filter; 2 3 Import java.io.IOException; 4 5 Import Javax.servlet.Filter; 6 Import Javax.servlet.FilterChain; 7 Import Javax.servlet.FilterConfig; 8 Import javax.servlet.ServletException; 9 Import javax.servlet.servletrequest;10 Import javax.servlet.servletresponse;11 Import JAVAX.SERVLET.HTTP.HTTPSERVLETREQUEST;12 Import javax.servlet.http.httpservletresponse;13/**15 * @ClassName: NOCACHEFILTER16 * @Description: Prevent browser from caching all dynamic pages * @author: Aloof Wolf * @date: 2014-8-31 PM 11:25:4019 *20 */public class N             Ocachefilter implements Filter {All public void DoFilter (ServletRequest req, Servletresponse resp,25 Filterchain chain) throws IOException, Servletexception {26//Turn ServletRequest strong to HttpServletRequest27 HttpS Ervletrequest request = (HttpServletRequest) req;28//Turn servletresponse strong into HttpServletResponse29 HttpServlet Response Response = (httpservletresponse) resp;30//Disable browser cache all dynamic pages Response.setdatEheader ("Expires",-1), Response.setheader ("Cache-control", "No-cache"), Response.setheader ("Pragma", "No-cache"); Chain.dofilter (request, response);}37. public void Init (filterconfig filter Config) throws Servletexception {}41-Destroy () {43 44}45}

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

1   <filter> 2       <filter-name>NoCacheFilter</filter-name> 3       <filter-class> Me.gacl.web.filter.nocachefilter</filter-class> 4   </filter> 5    6   <filter-mapping> 7       <filter-name>NoCacheFilter</filter-name> 8         <!--only intercepts JSP requests--9       <servlet-name >*.jsp</servlet-name>10   </filter-mapping>
Iii. controlling static resources in the browser cache page

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

 1 package me.gacl.web.filter; 2 3 Import java.io.IOException; 4 5 Import Javax.servlet.Filter; 6 Import Javax.servlet.FilterChain; 7 Import Javax.servlet.FilterConfig; 8 Import javax.servlet.ServletException; 9 Import javax.servlet.servletrequest;10 Import javax.servlet.servletresponse;11 Import JAVAX.SERVLET.HTTP.HTTPSERVLETREQUEST;12 Import javax.servlet.http.httpservletresponse;13/**15 * @ClassName: CACHEFILTER16 * @Description: Control Cache Filter17 * @author: Aloof Wolf * @date: 2014-9-1 PM 9:39:3819 *20 */public class Cachefi Lter implements Filter {filterconfig filterconfig;24 public void DoFilter (ServletRequest req, Ser Vletresponse resp,26 Filterchain chain) throws IOException, servletexception {httpservletreq          Uest request = (httpservletrequest) req;29 httpservletresponse response = (httpservletresponse) resp;30 31 1. Get the resource that the user wants to access, String URI = Request.getrequesturi (); 33 34//2.The suffix name of the resource to which the user wants to access the String ext = uri.substring (Uri.lastindexof (".") +1); 36 37//The time that the resource needs to be cached is filterconfig.getinitparameter (EXT), if (Time!=nul L) {Long T = Long.parselong (time) *3600*1000;41//Set Cache Response.setdateheader ("Expi      Res ", System.currenttimemillis () + t),}44 Chain.dofilter (request, response); 46 47}48 49     public void init (Filterconfig filterconfig) throws servletexception {this.filterconfig = filterconfig;51 }52 $ public void Destroy () {54 55}56}

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

 1 <!--Configure Cache Filters-2 <filter> 3 <filter-name>CacheFilter</filter-name> 4 <filt Er-class>me.gacl.web.filter.cachefilter</filter-class> 5 <!--Configure the Web resources to cache and the cache time, in hours--6 & Lt;init-param> 7 <param-name>css</param-name> 8 <param-value>4</param-value&gt ; 9 </init-param>10 <init-param>11 <param-name>jpg</param-name>12 &L t;param-value>1</param-value>13 </init-param>14 <init-param>15 &LT;PARAM-NAME&G t;js</param-name>16 <param-value>4</param-value>17 </init-param>18 <init-       param>19 <param-name>png</param-name>20 <param-value>4</param-value>21 &LT;/INIT-PARAM&GT;22 </filter>23 <!--Configure the suffix of the web resource to be cached-->24 <filter-mapping>25 <filter-n ame>cachefilter</filter-name>26 <url-pattern>*.jpg</url-pattern>27 </filter-mapping>28 <filter-mapp   Ing>30 <filter-name>cachefilter</filter-name>31 <url-pattern>*.css</url-pattern>32       </filter-mapping>33 <filter-mapping>35 <filter-name>cachefilter</filter-name>36 <url-pattern>*.js</url-pattern>37 </filter-mapping>38 <filter-mapping>39 <filter- Name>cachefilter</filter-name>40 <url-pattern>*.png</url-pattern>41 </filter-mapping>
IV. realization of Automatic user login

The idea is this:

1, after the user has successfully logged on, send a cookie named user to the client, the value of the cookie is the user name and MD5 encrypted password.
2, write a autologinfilter, this filter to check whether the user with a cookie named user, if any, then call the DAO query cookie whether the user name and password match the database, The match then stores the user object (that is, the login tag) to the session to enable the program to complete the automatic login.

The core code is as follows:

Controller to handle user logons: Loginservlet

 1 package Me.gacl.web.controller; 2 3 Import java.io.IOException; 4 5 Import Javax.servlet.ServletException; 6 Import Javax.servlet.http.Cookie; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 Import me.gacl.dao.userdao;12 import me.gacl.domain.user;13 Import me.gacl.util.webutils;14 public class Loginservlet extends HttpServlet {All public void doget (HTTPSERVLETR Equest request, HttpServletResponse response) throws Servletexception, IOException {. String use         Rname = Request.getparameter ("username"); String password = request.getparameter ("password"); 22 23             Userdao dao = new Userdao (), User user = Dao.find (username, password), if (user==null) {26 Request.setattribute ("message", "username or password is wrong!!  "); Request.getrequestdispatcher ("/message.jsp "). Forward (request, response); return;29       }30 request.getsession (). SetAttribute ("user", user), 31//Send automatic login cookie to the client browser for storage of the Sendauto     Logincookie (Request,response,user), Request.getrequestdispatcher ("/index.jsp"). Forward (request, response); 34     }35/**37 * @Method: SendAutoLoginCookie38 * @Description: Send automatic login cookie to client browser * @Anthor: Aloof Wolf 40 *41 * @param request42 * @param response43 * @param user44 * * * private void Sendautologincookie (Http ServletRequest request, HttpServletResponse response, user user) {if (Request.getparameter ("Logintime")!=null) {Logintime int = Integer.parseint (Request.getparameter ("Logintime")); 48//Create Cookie,cookie the name is AU Tologin, the value is the user's login username and password, which is used between the user name and the password. Split, password processed by MD5 encryption cookies = new Cookie ("Autologin", User.getusername ()             + "." + WEBUTILS.MD5 (User.getpassword ())); 50//Set the period of the cookie is cookie.setmaxage (logintime); 52 Set a valid path for a cookie 53             Cookie.setpath (Request.getcontextpath ()); 54//write cookie to client browser Response.addcookie (c             Ookie),}57}58, DoPost (httpservletrequest request, httpservletresponse response) 60 Throws Servletexception, IOException {doget (request, response); 63}64 65}

Filter to process user Auto-login: Autologinfilter

 1 package me.gacl.web.filter; 2 3 Import java.io.IOException; 4 5 Import Javax.servlet.Filter; 6 Import Javax.servlet.FilterChain; 7 Import Javax.servlet.FilterConfig; 8 Import javax.servlet.ServletException; 9 Import javax.servlet.servletrequest;10 Import javax.servlet.servletresponse;11 import javax.servlet.http.cookie;12 Import javax.servlet.http.httpservletrequest;13 Import javax.servlet.http.httpservletresponse;14 Import ME.GACL.DAO.USERDAO;16 Import me.gacl.domain.user;17 Import me.gacl.util.webutils;18 public class Autologinfilter Implements Filter {public void DoFilter (ServletRequest req, servletresponse resp,22 Filterchain Chai         N) throws IOException, servletexception {httpservletrequest request = (httpservletrequest) req;25 HttpServletResponse response = (HttpServletResponse) resp;26//If already logged in, direct chain.dofilter (request, response) put Line if (Request.getsession (). getattribute ("user")!=null) {chAin.dofilter (Request, response), return;30}31 32//1. Get the Authlogin cookie33 that the user brought over String value = null;34 Cookie cookies[] = Request.getcookies (), and a for (int i=0;cookies!=null &&amp ; i<cookies.length;i++) {cookies[i].getname () equals ("Autologin")) {Notoginseng value = Cookies[i]             . GetValue (); 38}39}40 41//2. Get the user name and password in the cookie if (value!=null) {43 String username = value.split ("\ \.") [0];44 String password = value.split ("\ \") [1];45 46//3. Call DAO to obtain the user's corresponding password, Userdao dao = new Userdao (); User user = Dao.find (username);//4 String Dbpassword = User.getpassword (); 50 51 MD5. Check the password that the user brought over and If the password in the database matches, the match is automatically logged in if (Password.equals (WEBUTILS.MD5 (Dbpassword))) {request.getsession (). s     Etattribute ("user", user); 54}55    }56 Chain.dofilter (request, response);}59, public void Destroy () {61 62 }63 public void init (Filterconfig filterconfig) throws Servletexception {65 66}67}

If you want to cancel automatic login, you can delete the automatic login cookie when the user logs off, the core code is as follows:

 1 package Me.gacl.web.controller; 2 3 Import java.io.IOException; 4 5 Import Javax.servlet.ServletException; 6 Import Javax.servlet.http.Cookie; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 One public class Cancelautologinservlet extends HttpServlet {p ublic void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept         Ion {15//Remove user16 request.getsession () stored in session. RemoveAttribute ("user"); 17//Remove automatic login Cookie18 Removeautologincookie (request,response); 19//Log off user after jump to login page request.getrequestdispatcher ("/login.js P "). Forward (request, Response)}22/**24 * @Method: RemoveAutoLoginCookie25 * @Description: Delete auto-login Co The way to delete cookies in okie,26 * Javaweb is to create a new cookie with the same name as the cookie to be deleted, 27 * Set the cookie's validity period of the newly created cookie to 0, the valid path and the The valid path of the deleted cookie is the same as * @AnthoR: Aloof Wolf *30 * @param request31 * @param response32 * * private void Removeautologincookie (HTTPSERVL Etrequest request, HttpServletResponse response) {34//Create a cookie35 cookie with the name autologin = new Cooki E ("Autologin", ""); 36//Set the cookie's validity period to 0, the command browser to delete the cookie37 cookie.setmaxage (0); 38//Set Pat for the cookie to be deleted H39 Cookie.setpath (Request.getcontextpath ()); Response.addcookie (cookie);}42 public Vo          ID doPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {45 Doget (request, response); 46}47}

These are some of the most common application scenarios for filters.

Javaweb Learning Summary (46)--filter (filter) Common applications

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.