过滤器是什么?过滤器能够对request和response进行拦截,就像河中加入一道大坝,可以选择性的拦截和放行。

最常用的地方是:统一对字符进行编码(它只对post提交方式有效)和权限验证。

模型

filter过滤器

如何创建一个设置字符的过滤器?

1、创建一个类,让他继承filter

2、重写doFilter方法

    @Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//设置字符集
		request.setCharacterEncoding(encoding);
                //开闸放行,如果不写,程序就停住不走了
		chain.doFilter(request, response);

	}

3、重写init方法

    @Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.encoding= filterConfig.getInitParameter("encoding");

	}

4、在web.xml中配置

	<filter>
		<filter-name>CharsetEncodingFilter</filter-name>
		<filter-class>
                    com.cxc.drp.util.filter.CharsetEncodingFilter
                </filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharsetEncodingFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

 

相关文章:

猜你喜欢
相关资源
相似解决方案