解决中文乱码问题

阅读更多
方法一、应用于解决form表单提交时的中文乱码

1.在web.xml中添加如下代码:
     
Set Character Encoding
com.sinosoft.common.EncodingFilter

encoding
GBK



Set Character Encoding
/*


2.EncodingFilter类代码如下:

public class EncodingFilter implements Filter {
    protected String encoding = null;
    protected FilterConfig filterConfig = null;
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // Select and set (if needed) the character encoding to be used
        String encoding = selectEncoding(request);
        if (encoding != null)
        {
            request.setCharacterEncoding(encoding);
        }
// Pass control on to the next filter
        chain.doFilter(request, response);
    }
    public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
    }
    protected String selectEncoding(ServletRequest request) {
        return (this.encoding);
    }
}

方法二、解决js传值中文乱码问题:
注:post提交需两次编码,一次解码。故在传值时需使用encodeURI两次编码,如encodeURI(encodeURI(Ph_Name))。解码时使用java.net.URLDecoder.decode(str,"UTF-8");

编码:
window.open("custNoList.jsp?Ph_Name="+encodeURI(encodeURI(Ph_Name))+"&Ph_Gender="+Ph_Gender+"&Ph_Birth_Date="+Ph_Birth_Date+"&Part_Id="+Part_Id,'nameCustNoList', "width="+intWidth+",height="+intHeight+",top="+intScreenY+",left="+intScreenX +",location=no,menubar=no,scrollbars=yes,toolbar=no,resizable=yes");

解码:
String Ph_Name = java.net.URLDecoder.decode(request.getParameter("Ph_Name"),"UTF-8");
java.net.URLEncoder.encode(craneName,"utf-8"),用此方法消除中文乱码时,要在tomcat的server.xml配置URIEncoding="utf-8"

或者

String UserName = new String(request.getParameter("UserName").getBytes("8859_1"),"UTF-8");
String UserName = new String(request.getParameter("UserName").getBytes("ISO-8859-1"),"UTF-8");

你可能感兴趣的:(Tomcat,.net,JSP,XML,Web)