The method of Filter Filter handling Chinese garbled code in Java

  • 2020-04-01 01:47:13
  • OfStack

Note: while learning to handle Chinese garbled code with selvert's filter filter, utf-8 was used to handle Chinese garbled code in the filter configuration initialization, while GBK was used in the submitted JSP page. Although both can be out of the Chinese garbled code, but it caused the processing of garbled code format is not consistent. So there's a compilation error.

Solution: use utf-8 or GBK everywhere


//The filter class
CharactorFilter.jsp
package cn.com.Filter;
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;
public class CharactorFilter implements Filter { //Inheriting the Filter class
    //A character encoding
    String encoding=null;
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        if(encoding!=null){
        // Set up the requestA character encoding
            request.setCharacterEncoding(encoding);
         // Set up the responseA character encoding
            response.setContentType("text/html;charset="+encoding);
        }
     //Pass it to the next filter
        chain.doFilter(request, response);
    }
    public void init(FilterConfig filterConfig) throws ServletException {
      //Gets the initialization parameter
        encoding=filterConfig.getInitParameter("encoding");
    }
    public void destroy() {
        // TODO Auto-generated method stub
        encoding=null;
    }
}

web.xml


 <filter>      <!-- Notice that this is filter , do not configure to servlet-->
    <filter-name>CharactorFilter</filter-name>    <!-- Filter name -->
   <filter-class>cn.com.Filter.CharactorFilter</filter-class>  <!-- The full class name of the filter -->  
     <init-param>   <!-- Initialization parameter -->  
         <param-name>encoding</param-name>  <!-- The parameter name -->  
         <param-value>utf-8</param-value>   <!-- The parameter value -->  
     </init-param>
  </filter>
  <filter-mapping> <!-- Filter mapping --> 
      <filter-name>CharactorFilter</filter-name><!-- Filter name -->   
      <url-pattern>/*</url-pattern><!--URL Map to all pages to handle garbled code -->  
      </filter-mapping>


Related articles: