Home > Java > Java Tutorial > body text

How does the java Filter handle Chinese garbled characters?

藏色散人
Release: 2020-04-11 10:03:43
Original
2164 people have browsed it

How does the java Filter handle Chinese garbled characters?

#How does the java Filter handle Chinese garbled characters?

Attention: When learning to use selvert's filter filter to process Chinese garbled characters, utf-8 was used to process Chinese garbled characters when the filter configuration was initialized, but gbk was 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;
    }
}
Copy after login

web.xml

      
    CharactorFilter    
   cn.com.Filter.CharactorFilter    
          
         encoding    
         utf-8     
     
  
    
      CharactorFilter   
      /*  
      
Copy after login

The above is the detailed content of How does the java Filter handle Chinese garbled characters?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!