Filter实现字符集统一设置
Filter实现字符集统一设置
其实是对request和response请求进行了拦截
1.创建Filter类,实现javax.Servlet接口
doFilter方法
- //设置字符集
- request.setCharacterEncoding("GB18030");
- //继续执行
- chain.doFilter(request, reponse);
2.配置到web.xml中,请求request时,对所有jsp servlet进行统一设置(拦截)
- <filter>
- <filter-name>CharsetEncodingFilter</filter-name>
- <filter-class>com.bgt.drp.util.filter.CharsetEncodingFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>CharsetEncodingFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>CharsetEncodingFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
为达到灵活配置,不用修改java代码就可以改变设置的字符集类型
可以将字符集放到配置文件中,通过读取配置文件获取
还可以配置Filter时,传参数(字符集作为参数),tomcat启动初始化时,获取到参数【采取】
1.配置Filter时,传参数<init-param>标签
- <filter>
- <filter-name>CharsetEncodingFilter</filter-name>
- <filter-class>com.bgt.drp.util.filter.CharsetEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>GBK</param-value>
- </init-param>
- </filter>
2.Init方法获取参数,doFilter设置字符集
- public class CharsetEncodingFilter implements Filter {
- private String encoding;
- @Override
- public void destroy() {
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse reponse,
- FilterChain chain) throws IOException, ServletException {
- //设置字符集
- request.setCharacterEncoding(encoding);
- //继续执行
- chain.doFilter(request, reponse);
- }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- this.encoding = filterConfig.getInitParameter("encoding");
- }
- }
每次request请求通过配置文件,都会拦截,读取参数,并完成对作用域字符集的统一设置,灵活可配置,避免重复
扩:
Filter可以看做是一种横切性的技术
提供一种声明式服务,可插拔
体现了职责链模式
转载自:https://blog.csdn.net/songxuemeng/article/details/52434847