tomcat中的一个过滤器例子

xiaoxiao2021-02-28  5

感谢:http://www.iteye.com/wiki/Struts/578-Struts原理与实践(5) 和Google

将所有的request的字符集也设置为UTF-8。虽然,我们可以在每个文件中加入这样的句子:request.setCharacterEncoding("UTF-8");来解决,但这样显得很麻烦。一种更简单的解决方法是使用filter。具体步骤如下: 在mystruts\WEB-INF\classes目录下再新建一个名为filters的目录,新建一个名为:SetCharacterEncodingFilter的类,并保存在该目录下。其实,这个类并不要您亲自来写,可以借用tomcat中的例子。现将该例子的程序节选如下: 

package 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;    import javax.servlet.UnavailableException;      public class SetCharacterEncodingFilter implements Filter {         //可以理解为默认编码,在web.xml中配置后读取存入     protected String encoding = null;           protected FilterConfig filterConfig = null;        protected boolean ignore = true;           public void destroy() {               this.encoding = null;            this.filterConfig = null;          }            public void doFilter(ServletRequest request, ServletResponse response,                             FilterChain chain)            throws IOException, ServletException {               // Conditionally select and set the character encoding to be used  //如果被忽略或者请求未设置编码,为了防止乱码,进行编码过滤           if (ignore || (request.getCharacterEncoding() == null)) {    //设置请求编码为web.xml中配置的编码类型             String encoding = selectEncoding(request);                if (encoding != null)                    request.setCharacterEncoding(encoding);           }              // Pass control on to the next filter  //由FilterChain进行过滤处理,而不是该Filter          chain.doFilter(request, response);         }      //主要从配置文件中读取配置项并进行赋值     public void init(FilterConfig filterConfig) throws ServletException {               this.filterConfig = filterConfig;    //从web.xml读取配置的编码,如gbk,utf-8等,赋值给encoding         this.encoding = filterConfig.getInitParameter("encoding");   //从web.xml读取是否忽略         String value = filterConfig.getInitParameter("ignore");          if (value == null)              this.ignore = true;          else if (value.equalsIgnoreCase("true"))              this.ignore = true;          else if (value.equalsIgnoreCase("yes"))                this.ignore = true;            else               this.ignore = false;          }     protected String selectEncoding(ServletRequest request) {               return (this.encoding);          }      <filter>       <filter-name>Set Character Encoding</filter-name>       <filter-class>filters.SetCharacterEncodingFilter</filter-class>       <init-param>         <param-name>encoding</param-name>         <param-value>UTF-8</param-value>       </init-param>     </filter>     <filter-mapping>       <filter-name>Set Character Encoding</filter-name>       <url-pattern>/*</url-pattern>   </filter-mapping>  
转载请注明原文地址: https://www.6miu.com/read-1150168.html

最新回复(0)