GET/POST方式的区别:
<body> <form action="/Demo04/RequestParamsServlet" method="GET/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">足球<br> <input type="submit" value="提交"> </form>
public class RequestParamsServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //设置request对象的解码方式 request.setCharacterEncoding("utf-8"); String name = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("用户名:" + name); System.out.println("密 码:" + password); // 获取参数名为“hobby”的值 String[] hobbys = request.getParameterValues("hobby"); System.out.print("爱好:"); for (int i = 0; i < hobbys.length; i++) { System.out.print(hobbys[i] + ","); } } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doGet(request, response); } }
观察控制台的效果可以发现:POST方式可以解决,而GET方式不能解决。
可以得出结论:setCharacterEncoding()方法只对POST提交方式有效。
对于GET方式,我们可以这样:
public class RequestParamsServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //设置request对象的解码方式 request.setCharacterEncoding("utf-8"); String name = request.getParameter("username"); name=new String(name.getBytes("iso8859-1"),"utf-8"); String password = request.getParameter("password"); System.out.println("用户名:" + name); System.out.println("密 码:" + password); // 获取参数名为“hobby”的值 String[] hobbys = request.getParameterValues("hobby"); System.out.print("爱好:"); for (int i = 0; i < hobbys.length; i++) { System.out.print(hobbys[i] + ","); } } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doGet(request, response); } }
添加name=new String(name.getBytes(“iso8859-1”),“utf-8”); 就是先用错误码表"iso8859-1"将用户名重新编码,然后使用utf-8进行解码。
当然还可以l了解一下通过配置Tomcat解决GET提交方式中文乱码问题:
在server.xml中的Connector节点下添加一个useBodyEncodingForURI="true"并在程序中调用response.setCharacterEncoding(“GBK”)。