问题描述:当使用<a href="admin_userinfo_update.jsp?relname=<%=userinfo.getRelname()%>">传递参数时,在admin_userinfo_update.jsp页面中用request.getParameter("relname")发生中文乱码。


解决一(已验证):

request.setCharacterEncoding("gb2312");
String str = request.getParameter("relname");
str=new String(str.getBytes("ISO-8859-1"),"gb2312");

注意编码格式一致:

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />



解决二:

修改Tomcat配置 Tomcat/conf/server.xml文件里的编码方式

1.更改服务器编码

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="GBK"/>

2.修改tomcat GET方式的编码

<Connector port="8080" ...... URIEncoding="UTF-8" useBodyEncodingForURI="true"/>


解决三:

在请求中的乱码问题,一般用filter来解决,直接写一个servlet实现Filter接口,实现方法doFilter

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 编码过滤器
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class CharaterFilter extends HttpServlet implements Filter {
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
((HttpServletRequest) arg0).setCharacterEncoding("utf-8");
((HttpServletResponse) arg1).setCharacterEncoding("utf-8");
arg2.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
在web.xml文件中配置,配置如下:
<filter>
<filter-name>charater</filter-name>
<filter-class>com.zyxs.filter.CharaterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charater</filter-name>
<url-pattern>/*</url-pattern>           <!--  /*表示过滤所有请求   -->
</filter-mapping>

分析:

tomcat默认的编码格式iso-8859-1,request取值时编码格式变了→造成中文乱码


拓展:

1.超链接多参数传递 relname=<%=userinfo.getRelname()%>&XXX=<%=%>

2.Tomcat 配置 技巧

http://blog.csdn.net/sunyujia/article/details/2027635