解决get和post请求提交数据中文乱码问题
目录
get请求乱码
Tomcat8以后不需要处理GET请求,默认是UTF-8编码!!!
乱码案例
一个简单的登录共能,将表单中的账号密码提交给Servlet
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>请输入账号密码登录</h2>
<form action="LoginServlet" method="get">
账号:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
提交给的Servlet
package com.zhujunwei.demo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取得用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username="+username);
System.out.println("password="+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Servlet取得用户名和密码并将他们打印在控制台。
结果
只有英文,控制台得到信息
username=admin
password=123456
用户名在出项中文时会出现乱码。
解决办法
方法一:进行转码
//取得用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//进行转码
username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
System.out.println("username="+username);
System.out.println("password="+password);
方法二:修改tomcat中conf/server.xml
找到
Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
修改为
Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
post请求乱码
解决办法:在取参数之前设置编码格式
// 取得用户名和密码
//解决post请求乱码
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username=" + username);
System.out.println("password=" + password);
---------------
我每一次回头,都感觉自己不够努力,所以我不再回头。
---------------