tomcat乱码

来源:互联网 发布:linux copy -命令 编辑:程序博客网 时间:2024/04/29 08:31

  

问题:
在java-tomcat-eclipse-mysql 环境中(其实什么环境不重要)
当页面提交以及action中通过request.getParameter的时候会出现乱码
方案一:
当你在ACTION中添加语句content = new String(request.getParameter("content").getBytes("ISO-8859-1"),"GB2312");
来对其进行转换是没有任何问题的
方案二:
Tomcat 的 Server.xml文件 的 Connector 添加 URIEncoding=“GBK”
方案三:
做个filter
方案二和三都存在一个问题就是在IE中仍然存在乱码的问题 但到了其他浏览器就没有问题了@
解决办法是把HTML中的content="text/html; charset=GBK"
 
JSP中也是如此!
现在专门讲一下filter:
先写个filter 假设放在com.DP.Filter包中
public class filter implements Filter {
 protected String encoding = null;
 
 protected FilterConfig filterConfig = null;
 
 protected boolean ignore = true;
 
 public void init(FilterConfig filterConfig) throws ServletException {
 // TODO Auto-generated method stub
 this.filterConfig = filterConfig;
 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;
 }
 
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
 // TODO Auto-generated method stub
   if (ignore || (request.getCharacterEncoding() == null)) {
   String encoding = selectEncoding(request);
   if (encoding != null)
    
    request.setCharacterEncoding(encoding);
    /*Enumeration test= request.getParameterNames(); 
    String name=null;
       String nameValue=null;
       while(test.hasMoreElements())
       {
        name=(String)test.nextElement();
        nameValue=new String(request.getParameter(name).getBytes("ISO-8859-1"),"GB2312");
        System.out.println("name***"+name+"***value***"+nameValue);
       } */
 }
 chain.doFilter(request, response);
 
 }
 
 public void destroy() {
 // TODO Auto-generated method stub
 this.encoding = null;
 this.filterConfig = null;
 }
 
 protected String selectEncoding(ServletRequest request) {
 
 return (this.encoding);
 
 }
 
}
然后设置web.xml,添加以下代码:(注意filter在web.xml中的放置顺序)
                <filter>
 <filter-name>filter</filter-name>
 <filter-class>com.DP.Filter.filter</filter-class>
 <init-param>
   <param-name>encoding</param-name>
   <param-value>GBK</param-value>
 </init-param>
 <init-param>
   <param-name>ignore</param-name>
   <param-value>true</param-value>
 </init-param>
 </filter>
 
 <filter-mapping>
 <filter-name>filter</filter-name>
 <url-pattern>*.do</url-pattern>
 </filter-mapping>
如此就解决了添加filter后的所有提交页面的乱码的问题!
原创粉丝点击