修改tomcat的conf/server.xml解决网页乱码

——后台
转码
str= new String(str.getBytes("iso8859-1"),"gb2312");
str= new String(str.getBytes("iso8859-1"),"GBK");
 
servlet中
response.setContentType("text/html; charset=GBK");

——前台
JSP中乱码
<%@ page language="java" contentType="text/html;charset=GBK" pageEncoding="GBK" %> 


——服务器 tomcat中
  更改 Tomcat\conf\server.xml,指定浏览器的编码格式为“简体中文”:

               connectionTimeout="20000"
               redirectPort="8443" />
改成
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="GBK"/>

 

——web.xml中添加一个过滤器

 
    CharacterEncodingFilter 
    com.worthtech.app.filter.CharacterEncodingFilter 
     
      encoding 
      UTF-8 
   
 
     
      ignore 
      true 
   
 
 
 
   
    CharacterEncodingFilter 
    /* 
 

 

 

java 代码

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 CharacterEncodingFilter implements Filter {  
 
    private String encoding=null;  
    private boolean ignore=true;  
      
    public void destroy() {  
        // TODO Auto-generated method stub  
        encoding=null;  
    }  
 
    /**  
       * 过滤请求,用户提交请求时起作用  
       */    
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
        // TODO Auto-generated method stub  
        if(ignore||request.getCharacterEncoding()==null){  
            String encoding=getEncoding();  
            if(encoding!=null){  
                request.setCharacterEncoding(encoding);  
            }  
        }  
//      System.out.println("encoding===="+encoding);  
        response.setContentType("text/html;charset="+encoding);  
//      do something here  
        //当前工作全部完成后,将请求放开给过滤器链的下一filter   
        chain.doFilter(request, response);  
    }  
 
    public void init(FilterConfig filterConfig) throws ServletException {  
        // TODO Auto-generated method stub  
        this.encoding=filterConfig.getInitParameter("encoding");  
        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 getEncoding(){  
        return this.encoding;  
    }  
}

你可能感兴趣的:(修改tomcat的conf/server.xml解决网页乱码)