在填写表单数据时,难免会输入中文,如姓名、公司名称等。由于HTML设置了浏览器在传递请求参数时,采用的编码方式是UTF-8,但在解码时采用的是默认的ISO8859-1,因此会导致乱码的出现。

解决POST方式提交中文乱码
在HttpServletRequest接口中,提供了一个setCharacterEncoding()方法,该方法用于设置request对象的解码方式。
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>表单</title>
</head>
<body>
<form action="/JavaEEDemo/request" method="post">
用户名:<input type="text" name="username"><br/>
密 码:<input type="password" name="password"><br/>
爱 好:
<input type="checkbox" name="hobby" value="sing">唱歌
<input type="checkbox" name="hobby" value="dance">跳舞
<input type="checkbox" name="hobby" value="football">足球
<input type="submit" value="提交">
</form>
</body>
</html>
后台:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("用户名:" + username);
System.out.println("密码:" + password);
//获取参数名为hobby的值
String[] hobbys = request.getParameterValues("hobby");
System.out.println("爱好:");
for (int i = 0; i < hobbys.length; i++) {
System.out.println(hobbys[i] + ", ");
}
}
点击提交,后台输出:
用户名:张三
密码:123456
爱好:
sing,
dance,
从上面的示例可以看出,控制台输出的参数信息没有出现乱码。
需要注意的是: 该 方 式 只 对 P O S T 方 式 有 效 \color{red}{该方式只对POST方式有效} 该方式只对POST方式有效,而对GET方式无效。
解决GET方式提交中文乱码
需要在获取到参数后,先用ISO8859-1解码,然后再使用UTF-8编码。
修改表单为GET提交方式:
<form action="/JavaEEDemo/request" method="get">
用户名:<input type="text" name="username"><br/>
密 码:<input type="password" name="password"><br/>
爱 好:
<input type="checkbox" name="hobby" value="sing">唱歌
<input type="checkbox" name="hobby" value="dance">跳舞
<input type="checkbox" name="hobby" value="football">足球
<input type="submit" value="提交">
</form>
修改后台doGet方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
username = new String(username.getBytes("iso8859-1"), "utf-8");
String password = request.getParameter("password");
System.out.println("用户名:" + username);
System.out.println("密码:" + password);
//获取参数名为hobby的值
String[] hobbys = request.getParameterValues("hobby");
System.out.println("爱好:");
for (int i = 0; i < hobbys.length; i++) {
System.out.println(hobbys[i] + ", ");
}
}
通过浏览器访问表单页面:
点击提交,后台输出:
用户名:小明
密码:123456
爱好:
dance,
football,