过滤器的作用:
对于整个项目进行统一编码格式的统一,假如项目有很多页面获取值 则需要每个页面都要设置编码格式,这这时候就要设置过滤器了,配置如下
需要用到: EncodingFilter java类;和web.xml
1.读取web.xml 文件中配置的WEB 应用初始化参数encoding
2.指定请求的字符编码为1 读取到的编码;
3.调用chain.doFilter()方法 "执行"请求
request.setCharacterEncoding("UTF-8");
package cn.hp.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; public class EncodingFilter implements Filter { String encoding = ""; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub res.setCharacterEncoding(encoding); req.setCharacterEncoding(encoding); chain.doFilter(req, res); } @Override public void init(FilterConfig config) throws ServletException { // TODO Auto-generated method stub encoding = config.getInitParameter("encoding"); } }
web.xml 配置文件:
1 <!-- 编码格式过滤器 --> 2 <filter> 3 <filter-name>EncodingFilter</filter-name> 4 <filter-class>cn.hp.filter.EncodingFilter</filter-class> 5 <init-param> 6 <param-name>encoding</param-name> 7 <param-value>UTF-8</param-value> 8 </init-param> 9 </filter> 10 <filter-mapping> 11 <filter-name>EncodingFilter</filter-name> 12 <url-pattern>/*</url-pattern> 13 </filter-mapping>