Filter (web basic learning Notes 21), web Learning notes
1. Introduction to Filters
2. Create a filter in Eclipse
3. Use the filter to set all web character encoding
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, servletException {// TODO Auto-generated method stub // place your code here // pass the request along the filter chain // request Encoding request. setCharacterEncoding ("UTF-8"); chain. doFilter (request, response); // response encoding response. setCharacterEncoding ("UTF-8 ");}
After using the filter settings, you do not need to set character encoding on the page separately.
Set in Web. xml
<filter> <display-name>CharacterEncodingFilter</display-name> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.pb.news.web.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<Filter-name> specifies a name for the filter. The content of this element cannot be blank.
The <filter-class> element is used to specify the full qualified class name of the filter.
The <init-param> element is used to specify initialization parameters for the filter. Its sub-element <param-name> specifies the parameter name and <param-value> specifies the parameter value.
In the filter, you can use the FilterConfig interface object to access initialization parameters. If the filter does not need to specify the initialization parameter, the <init-param> element does not need to be configured.
After you use Eclipse to create a filter, the above content is automatically added to web. xml. You can also manually add
Iv. Steps for using the filter
5. Filter Lifecycle
6. There can be multiple Filters-forming a filter chain
VII. application scenarios of filters