Home  >  Article  >  Java  >  Solution to java garbled filter

Solution to java garbled filter

藏色散人
藏色散人Original
2020-04-07 09:40:312005browse

Solution to java garbled filter

How to deal with Chinese garbled characters using Filter filter in java

Attention: When learning to use selvert filter When filter handles Chinese garbled characters, utf-8 is used to handle Chinese garbled characters when the filter configuration is initialized, but gbk is used in the submitted jsp page. Although both can produce Chinese garbled characters, they result in inconsistent formats for processing garbled characters. So the compilation error occurred.

Recommended tutorial: "java learning"

Solution: Use utf-8 or gbk everywhere

//过滤器类
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 { //继承Filter类
    //字符编码
    String encoding=null;
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        if(encoding!=null){
        //设置request字符编码
            request.setCharacterEncoding(encoding);
         //设置response字符编码
            response.setContentType("text/html;charset="+encoding);
        }
     //传递给下一个过滤器
        chain.doFilter(request, response);
    }
    public void init(FilterConfig filterConfig) throws ServletException {
      //获取初始化参数
        encoding=filterConfig.getInitParameter("encoding");
    }
    public void destroy() {
        // TODO Auto-generated method stub
        encoding=null;
    }
}

web.xml

<filter>      <!--注意这里是filter,不要配置成servlet-->
    <filter-name>CharactorFilter</filter-name>    <!--过滤器名称-->
   <filter-class>cn.com.Filter.CharactorFilter</filter-class>  <!--过滤器的完整类名-->  
     <init-param>   <!--初始化参数-->  
         <param-name>encoding</param-name>  <!--参数名称-->  
         <param-value>utf-8</param-value>   <!--参数值-->  
     </init-param>
  </filter>
  <filter-mapping> <!--过滤器映射--> 
      <filter-name>CharactorFilter</filter-name><!--过滤器名称-->   
      <url-pattern>/*</url-pattern><!--URL映射,给所有页面处理乱码-->  
      </filter-mapping>

The above is the detailed content of Solution to java garbled filter. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn