jsp中UTF-8乱码解决方案

jsp中UTF-8乱码解决方案

一、确保jsp页面中<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>和<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">编码为UTF-8;

二、post方式

配置字符过滤器

package  com.util.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;

/** */ /**
* 采用Filter统一设置处理字符集 
@author songfeng
@version 1.0
* Apr 1, 2010
*/

public   class  CharsetEncodingFilter  implements  Filter  {

private String encoding = "UTF-8";

public void destroy() {
}


public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
    FilterChain filterChain) 
throws IOException, ServletException {
   servletRequest.setCharacterEncoding(
this.encoding);
   filterChain.doFilter(servletRequest, servletResponse);
}


public void init(FilterConfig filterConfig) throws ServletException {
   
this.encoding = filterConfig.getInitParameter("encoding");
}

}

配置web.xml

< filter >
   
< filter-name > CharsetEncodingFilter </ filter-name >
   
< filter-class > com.util.filter.CharsetEncodingFilter </ filter-class >
   
< init-param >
    
< param-name > encoding </ param-name >
    
< param-value > UTF-8 </ param-value >
   
</ init-param >
</ filter >

< filter-mapping >
   
< filter-name > CharsetEncodingFilter </ filter-name >
   
< url-pattern > *.jsp </ url-pattern >
</ filter-mapping >

< filter-mapping >
   
< filter-name > CharsetEncodingFilter </ filter-name >
   
< url-pattern > /servlet/* </ url-pattern >
</ filter-mapping >

三、get方法

1、配置tomcat中server.xml

<Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" disableUploadTimeout="true" URIEncoding="UTF-8"/>

2、在要传递参数的时候进行转码(如不转码奇数中文字符最后一个字符乱码)

(1)JSP传值方式:
跳转页:
<a href=info.jsp?info="<%= java.net.URLEncoder.encode("中文汉字","GBK") %>">跳转</a>
接收页
<%
     String info_str = new String(request.getParameter("info"),"ISO8859-1");
     out.print(info_str); //输出接收值
%>
(2)JS传值方式:
先用encodeURI()进行编码
var p = "你好吗?";
var url = "aaa.jsp?param=" + encodeURI(p);
然后在服务器端要解码
<%
String param = request.getParameter("p");
param = new String(param.getBytes("ISO-8859-1"),"UTF-8");
%>
四、ajax乱码

在要传递中文参数的js中转码:encodeURIComponent(“×××”)

你可能感兴趣的:(jsp中UTF-8乱码解决方案)