本文共 2161 字,大约阅读时间需要 7 分钟。
在填写表单数据时,难免会输入中文,如姓名、公司名称等。由于HTML设置了浏览器在传递请求参数时,采用的编码方式是UTF-8,但在解码时采用的是默认的ISO8859-1,因此会导致乱码的出现。
在HttpServletRequest接口中,提供了一个setCharacterEncoding()方法,该方法用于设置request对象的解码方式。
request。setCharacterEncoding("utf-8");
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>表单
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方式无效。
需要在获取到参数后,先用ISO8859-1解码,然后再使用UTF-8编码。
name = new String(name.getBytes("iso8859-1"), "utf-8");
修改表单为GET提交方式:
修改后台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,
转载地址:http://lnsqb.baihongyu.com/