出现中文乱码的问题,一般的原因编码和和解码不一致造成的。



1  /*
2 乱码:编码和解码不一致导致的
3 GET:你好
4 POST:??????
5 tomcat版本:8.5及以上版本
6 GET请求方式,request对象使用的字符集默认为utf-8
7 POST请求方式,request对象使用的字符集默认为ISO8859-1
8 解决:
9 设置request对象的字符集为utf-8
10 request.setCharacterEncoding("utf-8");
11 tomcat版本:8.5以下版本(了解)
12 没有设置request的字符集
13 GET:??????
14 POST:??????
15 request.setCharacterEncoding("utf-8"); 只针对post方式有效
16 GET:??????
17 POST:你好
18 解决:
19 request对象默认字符集ISO8859-1
20 1.String类中的方法:可以把获取到的ISO8859-1编码的字符串转换为字节数组
21 byte[] getBytes(Charset charset) 使用指定的字符集把字符串转换为字节数组
22 2.String类的构造方法:把字节输出以UTF-8的方式解码为字符串
23 String(byte[] bytes, String charsetName) 把字节数组,根据字符集转换字符串
24 */

View Code

重点介绍一下response,我才用的tomcat8.5版本,一些详细的介绍在代码中。

具体的代码如下:(采用字节流与字符流)



1 import javax.servlet.ServletException;
2 import javax.servlet.annotation.WebServlet;
3 import javax.servlet.http.HttpServlet;
4 import javax.servlet.http.HttpServletRequest;
5 import javax.servlet.http.HttpServletResponse;
6 import java.io.IOException;
7
8 @WebServlet(urlPatterns = "/A_B")
9 public class DemoRes02 extends HttpServlet {
10
11 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
12 //test1(response);
13 test2(response);
14 }
15
16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17 doGet(request, response);
18 }
19
20 //使用字符流响应中文
21 public void test1(HttpServletResponse response) throws IOException {
22 //设置浏览器默认打开的时候采用的字符集
23 response.setContentType("text/html;charset=utf8");
24 response.getWriter().write("A_B,陈燕龙");
25 }
26 //使用字节流相应中文输出中文
27 public void test2(HttpServletResponse response) throws IOException {
28 //设置浏览器默认打开的时候采用的字符集
29 response.setHeader("Content-Type","text/html;chartset=utf-8");
30 response.getOutputStream().write("我,hello".getBytes());
31 }
32
33 }

View Code