JSP乱码问题总结

大家都知道,计算机只认识二进制的数字, 那么所谓各种字符的编码,其实就是对二进制数据的某种约定。如,ASCLISO88591GBKUnicodeUTF8。而乱码的产生就是在不同字符集转换的过程中出现的。比如在java中,内部使用的是Unicode编码,当JVM读取到中文时,它把GBK转化成Unicode进行处理,处理完输出时,再转化成GBK,读与写这两个过程是可逆的,按理不会产生乱码。但实际应用的情况就比较复杂,在WEB应用中,包括了浏览器,服务器,应用程序,数据库等等,它们之间的编码可能各不相同,没有一个合理的转换机制,乱码就产生了。下面就几种常见乱码问题做一下总结:

一、表单提交乱码:表单提交的默认字符串是以ISO-8859-1转化来的,ISO-8859-1不支持中文,由于找不到相应的编码,就会产生乱码。解决的办法可以在提交参数前调用request.setCharacterEncoding("UTF-8”)

二、输出中文时出现乱码:解决此问题可以在输入内容前加调用response.settCharacterEncoding("UTF-8”)。因引解决上述两各乱码问题,最好是写个过器,过滤器代码如下:

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;

import javax.servlet.http.HttpServlet;

 

public class CodeFilter extends HttpServlet implements Filter {

    private FilterConfig filterConfig;

    //Handle the passed-in FilterConfig

    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;

    }

 

    //Process the request/response pair

    public void doFilter(ServletRequest request, ServletResponse response,

                         FilterChain filterChain) {

        try {

          request.setCharacterEncoding("utf-8");

          response.setCharacterEncoding("utf-8");

          filterChain.doFilter(request, response);

        } catch (ServletException sx) {

            filterConfig.getServletContext().log(sx.getMessage());

        } catch (IOException iox) {

            filterConfig.getServletContext().log(iox.getMessage());

        }

    }

 

    //Clean up resources

    public void destroy() {

}

}

在Web.xml的<web-app></web-app>中加入如下代码:

<filter>

     <filter-name>codeFilter</filter-name>

     <filter-class>filter.CodeFilter</filter-class>

    </filter>

    <filter-mapping>

     <filter-name>codeFilter</filter-name>

     <url-pattern>*.*</url-pattern>   

    </filter-mapping>

三、地址栏中传中文乱码的问题:例如a.jsp?name=”张三。解决此问题需要做两点:

      a.在传参数之前先把参数进行转码:java.net.URLEncoder.encode(name);在取值时用java.net.URLDncoder.dncode(name);再转回中文。

      b.在Tomcat目录àconf目录àserver.xml里找到:(我的是Tomcat6.0

<Connector port="8080" protocol="HTTP/1.1"

               maxThreads="150" connectionTimeout="20000"

               redirectPort="8443"  <!—在里边加上这个参数---> URIEncoding=”utf-8”/>

四、如果前几各方法没有效果,不防试试这个:String name=new String(request.getParameter(“name”).getBytes(“ISO-8859-1”),”UTF-8”);

五、往磁盘上写文件时, 由于写入时默认是本机编码,虽然所取到的值是UTF-8编码,但写入时依然按本机编码。解决方法:

FileOutputStream fileoutputstream = new FileOutputStream(“文件名”);

DataOutputStream dos = new DataOutputStream(fileoutputstream);

dos.writeUTF(“内容”);

os.close();

六、往数据库写入时出现乱码,解决办法:首先确定你在插入数据库之前是中文 ,然后在数据库连接字串(URL)后加上useUnicode=true&characterEncoding=utf-8

以上属于个人总结,希望各位多提宝贵意见!

 

猜你喜欢

转载自tomfish88.iteye.com/blog/1107214