Servlet请求参数乱码解决方法

先写一个简单的JSP,里面有两种提交参数的方式:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="TestServlet?getParam=中文">GET</a>
	<form action="TestServlet" method="post">
		<input type="hidden" name="postParam" value="中文"/>
		<input type="submit" value="POST"/>
	</form>
</body>
</html>

一、Tomcat

这里强调一点,在此使用的tomcat没有经过任何的修改与配置。
当页面通过两种方式请求Servlet的时候,参数的编码原本为UTF-8,在通过HTTP服务将请求发送出去的时候,会将参数重新按照ISO-8859-1编码后发送。因此,不管GET或POST方式,Servlet接收到的参数数据的编码均为ISO-8859-1,必须重新转码为UTF-8,才能正确显示中文参数。
1、GET方式的请求与接收过程
页面中参数“getParam=中文”的编码原本为UTF-8,当用GET方式发送参数的时候,参数值会被Web服务器从UTF-8转码为ISO-8859-1。
Servlet接收到的GET请求参数的编码当然为ISO-8859-1了,对于中文肯定显示不了,因此要将ISO-8859-1转换为UTF-8就可以正常显示中文了。
String getParam = request.getParameter("getParam");
getParam = new String(getParam.getBytes("ISO8859-1"), "UTF-8");
 
2、POST方式请求与接收过程
页面中参数“param=中文”的编码原本为UTF-8,当点击页面中提交按钮后,参数会以UTF-8编码格式发送给Servlet,因此Servlet接收参数的时候必须将请求的编码明确设定为UTF-8,这样才能正确接收中文。
request.setCharacterEncoding("UTF-8");
String postParam = request.getParameter("postParam");
或
String param = request.getParameter("postParam");
String x = new String(param.getBytes("ISO-8859-1"), "UTF-8");
 
 二、Enterprise Application Project在JBoss下
这种类型的项目无论是通过post方式还是通过get方式提交的中文,都只能使用如下的方法解决乱码的问题:
String name = request.getParameter("name");
name = new String(name.getBytes("ISO8859-1"), "UTF-8");
String code = request.getParameter("code");
code = new String(code.getBytes("ISO8859-1"), "UTF-8");
 设置request的characterEncoding的方式无法解决乱码的问题。
本文转自:

猜你喜欢

转载自guoying252166655.iteye.com/blog/2069037