日期:2014-05-16 浏览次数:20458 次
参考Tomcat服务器目录webapps的examples示例
详细配置步骤:
1.配置web.xm文件,在web-app标签内添加过滤器的配置<filter>和<filter-mapping>
<!--中文乱码处理过滤--> <filter> <filter-name>EncodingFilter</filter-name><!--过滤器名称,自己起 --> <filter-class>com.filters.SetCharacterEncodingFilter</filter-class><!--过滤器类名称,包括包名一致、写全 --> <init-param><!--初始化参数,要指定的字符集编码 --> <param-name>encoding</param-name><!--参数名称 --> <param-value>GBK</param-value><!--参数值 --> </init-param> <init-param><!--初始化参数,指定是否忽略大小写 --> <param-name>ignore</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> <!--“/*”表示项目下所有资源 --> </filter-mapping> <!--中文乱码处理过滤 -->
2.实现过滤器代码,创建一个SetCharacterEncodingFilter类
package com.filters; 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; /** * 自定义字符处理过滤器 * 参考自Tomcat目录webapps\examples\WEB-INF\classes\filters * @author coderlu * @since 2012-12-10 */ public class SetCharacterEncodingFilter implements Filter { protected FilterConfig filterConfig = null; //初始化配置 protected String encoding = null; //接收字符编码 protected boolean ignore = true; //是否忽略大小写 /* 析构函数 * @see javax.servlet.Filter#destroy() */ @Override public void destroy() { this.encoding = null; this.filterConfig = null; } /* 执行过滤操作 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (ignore || (request.getCharacterEncoding() == null)) { String encoding = selectEncoding(request); //如果为空先从web.xml中得到 if (encoding != null){ request.setCharacterEncoding(encoding); //设置字符集编码 } } chain.doFilter(request, response); } /* 初始化过滤器 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); //从web.xml文件中读取encoding的值 String value = filterConfig.getInitParameter("ignore"); //从web.xml文件中读取ignore的值 //以下三种情况均为忽略大小写 if (value == null) this.ignore = true; else if (value.eq