您的位置:首页 > 产品设计 > UI/UE

Servlet学习笔记—request获得参数中文乱码问题解决

2017-11-04 10:00 597 查看

一、使用post请求方式的时候

html页面如下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>中文乱码示例</h1>
<form action="/www/demo" method="post">
姓名:<input name="name" type="text"><br>
<input type="submit" value="提交">
</form>
</body>
</html>


当处理post请求如下的时候,会出现中文乱码的问题

String name = req.getParameter("name");
System.out.println(name);


出现中文乱码问题的原因是由于html页面的编码方式是UTF-8,而在处理post参数的时候,默认是使用ISO-8859-1这种拉丁文编码方式,因此会出现中文乱码的问题

解决方式一(比较麻烦,不推荐):

        String name = req.getParameter("name");
System.out.println(name);
name=new String(name.getBytes("ISO-8859-1"),"UTF-8");//重新用utf-8来编码
System.out.println(name);


解决方式二(推荐使用):

在处理post参数请求的时候,指定用UTF-8这种编码方式,就不会出现乱码的情况(注意:使用这种方式的时候一定要在所有的获取post参数的方式之前)

//在获取参数之前,先指定UTF-8的编码方式,这样以后获取post参数的时候,都会统一使用UTF-8的编码方式
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name"); System.out.println(name);


二、使用get请求方式的时候

在使用tomcat8.x及以上版本的时候没有中文乱码的问题

html页面如下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>中文乱码示例</h1>
<a href="/wwwz/demo?describe=中文乱码">点击发送get请求</a>
</body>
</html>


解决方式一(比较麻烦,不推荐):

String describe = req.getParameter("describe");
describe=new String(describe.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(describe);


解决方式二(推荐使用):

修改tomcat服务器的server.xml文件,在Connector节点加入URIEncoding=”UTF-8”

如下:

<Connector connectionTimeout="20000"
port="8080" protocol="HTTP/1.1"
URIEncoding="UTF-8"
redirectPort="8443"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  servlet 乱码