In enterprise development, the most common is the Javaweb project, there is a Web project is unavoidable and background dealing with, such as I send new requests from the JSP page to the background, the background may be servlet, struts2, SPRINGMVC, etc., there is a problem, In the Sent parameter value if contains Chinese often to the background you found that will be garbled, of course, you can get the value after the background to re-encode the value, but if you want to re-encode each time, it will be very troublesome, here is a simple way to introduce, hope can be useful to you.
Filter
Filter is called filters and is a technique in Java servlet that allows us to filter the resources of the Web server to be accessed, for example, from the Internet
You can see that to add the filter, to access the Web resources must pass through the filter, if there is no filter then we can directly access the Web resources, this is the role of the filter, that can control access to resources, for example, can monitor the user access to the URL, you can prohibit the user not logged in Access, There is, of course, a point where the character set can be filtered. Okay, get to the chase.
Filter development
There are two steps to developing a filter
1, Write Java class implementation Javax.servlet.Filter interface
2. Register Filter
Writing the filter implementation class
First, the filter interface has three methods: Init, Destory, DoFilter
Init
When the filter is created, the filter is created with the Web server responsible, the filter is created when the Web server is started, and the Init method of the filter is executed, because the filter is only created once, so the Init method is only called once, In this method, you can obtain the initialization parameters when the registration is obtained by Filterconfig, which provides the following methods:
String getfiltername (): Gets the name of the filter.
String Getinitparameter (string name): Returns the value of the initialization parameter for the name specified in the deployment description. Returns null if it does not exist.
Enumeration Getinitparameternames (): Returns an enumeration collection of the names of all initialization parameters for the filter.
Public ServletContext Getservletcontext (): Returns a reference to the Servlet context object.
Destory
The Web server calls the Destory method to destroy the filter, which executes only once during the filter's lifetime, freeing the resources used in the filter, such as database connections.
DoFilter
This method is the key to the whole filter, the work we are going to do is mainly done in this method, this method provides three parameters: ServletRequest req, Servletresponse resp,
Filterchain chain; chain parameter is the filter chain, If we want the request to continue down we must call the Chain.dofilter method so that the request is passed down and we can choose when to call the Chain.dofilter method based on our business choice.
Second, register filter
The so-called registration filter is to let the Web server know the filter, let the filter function, need to re-register in XML, the specific way to register can refer to the example below.
Character Filter
The filter code is as follows:
1 PackageCom.cn.imooc.filter;2 3 Importjava.io.IOException;4 5 ImportJavax.servlet.Filter;6 ImportJavax.servlet.FilterChain;7 ImportJavax.servlet.FilterConfig;8 Importjavax.servlet.ServletException;9 Importjavax.servlet.ServletRequest;Ten ImportJavax.servlet.ServletResponse; One Importjavax.servlet.http.HttpServletRequest; A ImportJavax.servlet.http.HttpServletResponse; - - Public classSetcharacterencodingfilterImplementsFilter { the - //Store encoding format information - PrivateString encode =NULL; - @Override + Public voiddestroy () { - //TODO auto-generated Method Stub + A } at - @Override - Public voidDoFilter (servletrequest req, Servletresponse resp, -Filterchain chain)throwsIOException, servletexception { - //TODO auto-generated Method Stub - in //Conversion -HttpServletRequest request =(httpservletrequest) req; toHttpServletResponse response =(HttpServletResponse) resp; + - /* the * Determine if encoded format information is configured in the Web. xml File * * If blank, the encoding format is set to the encoding format in the configuration file $ * Otherwise the encoding format is set to Utf-8
Panax Notoginseng */ - if( This. Encode! =NULL&&! This. Encode.equals ("")){ theRequest.setcharacterencoding ( This. encode); +Response.setcharacterencoding ( This. encode); A}Else{ theRequest.setcharacterencoding ("Utf-8"); +Response.setcharacterencoding ("Utf-8"); - } $ $ /* - * Use the Dofilter method to invoke the next filter or target resource (servlet or JSP page) in the chain. - * Chain.dofilter handles the remainder of the filter (if any), eventually processing the requested servlet or JSP page. the */ - Chain.dofilter (request, response);Wuyi the } - Wu @Override - Public voidInit (Filterconfig arg0)throwsservletexception { About //TODO auto-generated Method Stub $ - This. Encode=arg0.getinitparameter ("Encode"); -System.out.println ("This.encode:" +encode); - } A +}
In the Init method, get the configured initialization parameter "encode", convert the request to Httpserevletrequest and HttpServletResponse, then set the encoding, and finally call Chain.dofilter (request, Response) method, which enables the filtering of the encoding.
Register the filter as follows, in Web. xml:
1<!--filter configuration information--2<filter>3<filter-name>SetCharacterEncodingFilter</filter-name>4<!--filter Set encoding file--5<filter-class>com.cn.imooc.filter.setcharacterencodingfilter</filter-class>6<init-param>7<!--Init-param element defines the initialization parameters of the filter--8<description> set name and encoding type for parameters and values </description>9<param-name>encode</param-name>Ten<param-value>utf-8</param-value> One</init-param> A</filter> -<filter-mapping> -<!--filter-mapping tells the container that all requests that match the pattern should be allowed through the access control filter. theAll access with the end of the. Action is filtered first through the filter file- -<filter-name>SetCharacterEncodingFilter</filter-name> -<url-pattern>*.action</url-pattern> -</filter-mapping>
At the time of registering the filter we configured the initialization parameters, set to Utf-8, in the blocked URL, and intercept all the URL requests ending with the action.
With the code above, the requested encoding can be set uniformly
There is no place to welcome, thank you!
Java development process from the foreground to the background Chinese garbled "filter"