post乱码
post请求,控制台输出乱码,因为http请求传输数据遵循TCP协议,为unicode,字节流传输,一个汉字占3~4个字节,而tomcat解析时默认ISO8859-1解析,转换异常
public class PostServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决post提交时(在请求头中)的中文乱码问题,其无法解决get提交(在地址栏里)时的中文乱码
//setCharacterEncoding()方法设置了请求正文中的字符编码
req.setCharacterEncoding("utf-8");
String name=req.getParameter("name");
System.out.println("name===="+name);
}
}
get请求乱码
tomcat9解决了get方式的中文乱码问题,无需处理,tomcat7没有解决
方法一:在tomcat服务器的conf/server.xml中的添加地址编码格式设定 URIEncoding="UTF-8"
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
方法二:
缺点:每个数据都需要进行打散和组装的过程,过于麻烦
优点:适用于get和post两种请求方式
public class GetServlet extends HttpServlet {
//对于请求中的中文乱码的万能解决方案,get post通用方式
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//这里接收到的name,其字符编码为ISO8859-1
String name=req.getParameter("name");
//打散:将name字符串按照原编码进行打散
byte[] bytes = name.getBytes("ISO8859-1");
//组装:将byte字节数组按照指定编码进行组装,组装为String
name=new String(bytes,"utf-8");
}
}
<body>
<form method="GetServlet或PostServlet" action="post或get">
姓名:<input type="text" name="name"/><br/>
年龄:<input type="text" name="age"><br/>
<input type="submit" value="提交">
</form>
</body>
response响应乱码
public class response_printWriter extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//响应中文乱码的解决
//设置响应的MIME类型,例如:video/MP4,image/jpg
//其中可以指定MIME的字符编码,即响应体的字符编码
resp.setContentType("text/html;charset=utf-8");
//setCharacterEncoding使用前提:
//1.必须设置在获取输出流之前 2.之前必须要先使用setContentType()方法设置MIME
// 作用:修改或覆盖setContentType()设置指定MIME的字符编码
resp.setCharacterEncoding("utf-8");
//获取标准输出流
PrintWriter out = resp.getWriter();
out.print("中国");
}
}
重定向数据传递乱码
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name=req.getParameter("name");
//解决中文乱码问题
byte[] bytes = name.getBytes("ISO8859-1");
name=new String(bytes,"utf-8");
//重定向无法使用request存放数据,无效(错误示范)
req.setAttribute("name",name);
//编码:类似打散成为一个一个的字节,对请求头的设置
name= URLEncoder.encode(name,"UTF-8");
//重定向,请求此servlet相当于请求了两次,get请求的提交方式
resp.sendRedirect("other?name="+name+"&password=15");
}
}
public class other extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String password = req.getParameter("password");
String name=req.getParameter("name");
//解码:组装
name = URLDecoder.decode("name", "utf-8");
//对中文乱码问题的解决(又经历了一次get请求)
name=new String(name.getBytes("ISO8859-1"),"UTF-8");
System.out.println("name====="+name);
PrintWriter out = resp.getWriter();
out.print(name+"=========="+password);
out.print("this is other page");
}
}
以上内容配置文件省略,可能会有错误,期望指正。^_^