前面我们看了页面本身内容乱码的解决,这一节我们看一下前台页面请求到后台时中文乱码的解决方式。
1、前提约束
- 创建一个springmvc项目 https://www.jianshu.com/p/7458c2af1199
2、操作步骤
- 在web文件夹下创建一个文件login.html,内容如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/user/login" method="get">
<input type="text" value="张力" />
<input type="submit" value="提交"/>
</form>
<form action="/user/login" method="post">
<input type="text" value="张力" />
<input type="submit" value="提交1"/>
</form>
</body>
</html>
- 在src文件夹下创建UserController.java,内容如下:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
public class UserController{
@RequestMapping(value = "/user/login",method = RequestMethod.GET)
public void userLogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
//下面这一句话保证了请求数据的不乱码
name = new String(name.getBytes("ISO-8859-1"),"utf-8");
//下面这一句话保证了响应数据的不乱码
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(name);
}
@RequestMapping(value = "/user/login",method = RequestMethod.POST)
public void userLogin1(HttpServletRequest request,HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
//下面这一句话保证了请求数据的不乱码
name = new String(name.getBytes("ISO-8859-1"),"utf-8");
//下面这一句话保证了响应数据的不乱码
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(name);
}
}
- 启动tomcat,测试
点击登录页面上的"提交"或者"提交1"按钮,“张力”都能正常显示到页面。