都快2020了,以GET方式提交表单不需要转码了!!
在很多时候,由于编码问题导致的乱码问题很常见,因为GBK,iso-8859-1等编码不支持中文
1.以下是我的测试代码:
package com.lcl.encoder;
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 ErrorCode extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request.setCharacterEncoding("utf-8");
//将iso-8859-1转码为utf-8
String name = new String (request.getParameter("name").getBytes("iso-8859-1"),"utf-8");
String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");
System.out.println(request.getMethod()+"以方式提交表单");
System.out.println(name+":"+password);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以GET方式提交出现了乱码
以POST方式提交
2.总结
1.以GET方式提交服务器使用了utf-8编码,所以不需要改编码
2.以POST方式提交,服务器使用iso-8859-1编码
3.解决方法
1.setCharacterEncoding方法
//设置编码为utf-8
request.setCharacterEncoding("utf-8");
2.手动解码,然后转码
//方法一
String name = request.getParameter("name");
name = URLEncoder.encode(name,"iso-8859-1");
name = URLDecoder.decode(name, "utf-8");
//方法二
String name = request.getParameter("name");
name = new String (name.getBytes("iso-8859-1"),"utf-8");