JAVA Web项目的编码过滤器

首先写一个EncodeFilter的过滤类:

package com.djtu.wy.common;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    public class EncodeFilter implements Filter{

     String encoding = null;
     FilterConfig filterConfig = null;

     
     public void destroy() {
      this.encoding = null;
      this.filterConfig = null;
     }

     public void doFilter(ServletRequest arg0, ServletResponse arg1,
       FilterChain arg2) throws IOException, ServletException {
      
      HttpServletRequest request = (HttpServletRequest) arg0;
            HttpServletResponse response = (HttpServletResponse) arg1;
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html; charset="+encoding);
           
            arg2.doFilter(arg0,arg1);
     }

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

 

而后在web.xml文件中进行配置:

     <filter>
   <filter-name>EncodeFilter</filter-name>
   <filter-class>com.djtu.wy.common.EncodeFilter</filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
   </init-param>
  </filter>
  
  <filter-mapping>
   <filter-name>EncodeFilter</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>

 

之后就大功告成啦!

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。