The filter is used in the process of making a DRP. the other day, Chang and Huanhuan introduced the idea of AOP to us in a small conference room, using the filter to think of both particularly similar.
such as:
in our normal programming, each line is called from top to bottom, and filter is "cut a knife" across every complete call. By configuration, it can filter arbitrary code paths.
Here's an example of transcoding/setting the character set as a quick look at how to use filter.
Create filter
Charsetencodingfilter.java
Package Com.drp.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;/** using filter to process filter * @author Danny * */public class Charsetencodingfilter Implements Filter {@Overridepublic void Destroy () {} @Overridepublic void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {System.out.println (" Charsetencodingfilter---->>>>filter start "); Request.setcharacterencoding (" Utf-8 ") ; Sets the character set Chain.dofilter (request, response); Continue execution of System.out.println ("charsetencodingfilter---->>>>filter End");} @Overridepublic void init (Filterconfig arg0) throws servletexception {}}
Configure Filter
Xml
<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "3.0" 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_3_0.xsd "> <filter> <filter-name> Charsetencodingfilter</filter-name> <filter-class>com.drp.filter.charsetencodingfilter</ filter-class> </filter> <filter-mapping><!--This filter filters all JSP pages-- < filter-name>charsetencodingfilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping></web-app>
The purpose of this configuration is that this filter has the effect of setting the character set for all JSP pages, and the Dofilter () method in the filter is executed every time the JSP page is accessed, so that each time the JSP page is accessed, You can see the Dofilter method output in the console "charsetencodingfilter---->>>>begin" and "charsetencodingfilter---->> >>end ".
At this point, regardless of which JSP page is accessed, it will set its character set beforehand, without having to set each page separately.
Use and configuration of Java filter--filter