Servlet learning notes (8) -- improved compilation of custom filters: custom implementation filterchain

Source: Internet
Author: User

Note 6 implements three filters: character encoding filtering, logon permission filtering, and sensitive word filtering. However, there is a drawback that the filtering order is limited, and request filtering cannot be implemented first, the last response filter, and the filtering order of the items in the middle cannot be changed dynamically. So here is an improvement to implement a filtering order of filterchain.

The execution sequence of multiple filters is carefully explained in this blog. To sum up, the execution sequence of multiple filters is based on the Web. different <filter-mapping> sequences in XML are executed successively, for example:

<?xml version="1.0" encoding="UTF-8"?>   <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">       <welcome-file-list>           <welcome-file>index.jsp</welcome-file>       </welcome-file-list>       <filter>           <filter-name>firstFilter</filter-name>           <filter-class>com.test.filter.FirstFilter</filter-class>       </filter>       <filter>           <filter-name>secondFilter</filter-name>           <filter-class>com.test.filter.SecondFilter</filter-class>       </filter>       <filter-mapping>           <filter-name>secondFilter</filter-name>           <url-pattern>/*</url-pattern>       </filter-mapping>       <filter-mapping>           <filter-name>firstFilter</filter-name>           <url-pattern>/*</url-pattern>       </filter-mapping>         <servlet>           <servlet-name>firstServlet</servlet-name>           <servlet-class>com.alimama.servlet.FirstServlet</servlet-class>       </servlet>       <servlet-mapping>           <servlet-name>firstServlet</servlet-name>           <url-pattern>/firstServlet</url-pattern>       </servlet-mapping>   </web-app>   

Secondfilter is executed first, and then firstfilter is executed.

The following is a piece of dofilter code to implement the filter interface. User-defined filters all implement this interface:

 public void doFilter(ServletRequest request, ServletResponse response,               FilterChain chain) throws IOException, ServletException {           System.out.println("before invoke secondFilter's chain.doFilter() ..");           chain.doFilter(request, response);           System.out.println("after invoke secondFilter's chain.doFilter() ..");       }   

We can see the chain. dofilter (request, response) in the fourth line; this code is the core of the filter technology in servlet. Its main function is to pass requests to the next filter. Instead of initializing all the filter objects at once.

Based on this idea, I defined a filterchain to implement the filtering order of multiple filters.

//FilterChain.javapackage lewa;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class FilterChain {//private static final String[] filters={"LoginFilter","WordFilter"};private static final Filter[] filters={new LoginFilter(),new WordFilter()};private static int count=0;public void doFilter(ServletRequest request,ServletResponse response,FilterChain fc) throws InstantiationException, IllegalAccessException, Exception{if(count<filters.length){//Class<Filter> cls=(Class<Filter>)Class.forName(filters[count]);//cls.doFilter(request, response);filters[count++].doFilter(request, response, fc);}}}

You can define the order of the filter instances in static member variables filters. To change the filter order in the future, you only need to change the string array.

Other filters have also been changed:

//Filter.javapackage lewa;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public interface Filter {public void init();public void doFilter(ServletRequest reuqest,ServletResponse response,FilterChain fc)throws Exception;public void destroy();}

//EncodingFilter.javapackage lewa;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class EncodingFilter implements Filter{@Overridepublic void init() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest reuqest, ServletResponse response,FilterChain fc)throws InstantiationException, IllegalAccessException, Exception{// TODO Auto-generated method stubreuqest.setCharacterEncoding("UTF-8");fc.doFilter(reuqest, response,fc);response.setContentType("text/html;charset=UTF-8");}@Overridepublic void destroy() {// TODO Auto-generated method stub}}

// Loginfilter. javapackage Lewa; import javax. servlet. servletrequest; import javax. servlet. servletresponse; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession; public class loginfilter implements filter {public loginfilter () {}@ overridepublic void Init () {// todo auto-generated method stub }@ overridepublic void dofilter (servletre Quest reuqest, servletresponse response, filterchain FC) throws exception {// todo auto-generated method returns Req = (httpservletrequest) reuqest; httpservletresponse resp = (response) response; httpsession session = req. getsession (); If (Session. getattribute ("username") = NULL) {resp. sendredirect ("login.html");} else {FC. dofilter (reuqest, response, FC); // here there must be an else. The next filter cannot be executed directly, because if If you do not log on to the console, you do not need to filter sensitive words. If you try not to add else, you will find that messages are redirected to the logon page before logon. After logging on to the logon page, you will return to the message page, at this time, Count does not meet Count <filters. length, so sensitive word filtering will not be executed at this time. }}@ Overridepublic void destroy () {// todo auto-generated method stub }}

//WordFilter.javapackage lewa;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Properties;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class WordFilter implements Filter{private static Pattern pattern=null;public static String str=null;private void loadKeyWordProperties(){StringBuffer patternBuffer = new StringBuffer();try{InputStream in =WordFilter.class.getClassLoader().getResourceAsStream("words.properties");Properties properties = new Properties();properties.load(in);Enumeration<?> enu=properties.propertyNames();while(enu.hasMoreElements()){patternBuffer.append((String)enu.nextElement()+"|");}patternBuffer.deleteCharAt(patternBuffer.length()-1);pattern = Pattern.compile(new String(patternBuffer.toString().getBytes("ISO-8859-1"),"UTF-8"));}catch(IOException e){e.printStackTrace();}}@Overridepublic void init() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest reuqest, ServletResponse response,FilterChain fc)throws InstantiationException, IllegalAccessException, Exception {// TODO Auto-generated method stubloadKeyWordProperties();str=reuqest.getParameter("liuyan");try{Matcher m=pattern.matcher(str);str=m.replaceAll("**");}catch(Exception e){e.printStackTrace();}fc.doFilter(reuqest, response,fc);}@Overridepublic void destroy() {// TODO Auto-generated method stub}}

Finally, the Code changes in the servlet:

Package Lewa; import Java. io. ioexception; import Java. io. printwriter; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession;/*** Servlet implementation class summary */public class summary extends httpservlet {Private Static final long serialversionuid = 1l;/*** @ see httpservlet # httpservlet () */Public Summary () {super (); // todo auto-generated constructor stub}/*** @ see httpservlet # doget (httpservletrequest request, response) */protected void doget (httpservletrequest request, response) throws servletexception, ioexception {// todo auto-generated method stub}/*** @ see httpservlet # dopost (httpservletre Quest request, incluresponse) */protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// todo auto-generated method stubfilter filter = new encodingfilter (); filterchain fc = new filterchain (); try {filter. dofilter (request, response, FC);} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();} printwriter Out = response. getwriter (); httpsession session = request. getsession (); string name = (string) Session. getattribute ("username"); If (name! = NULL &&! "". Equals (name) {name = new string (name. getbytes ("ISO-8859-1"), "UTF-8");} Out. println ("<HTML> 

Write the source code for the custom filter chain.

Hope you can give me more advice ~~



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.