为什么会产生乱码?
客户端向服务器端发起请求(request),服务器端响应客户端的请求后做出应答(response)。服务器端和客户端默认使用的“iso8859-1”来编码。要想不出现乱码,服务器客服端编码格式需要一致。解决中文乱码使用“utf-8”
返回值客户端中文乱码
response.setCharacterEncoding(“utf-8”);
response.setContentType(“application/json;charset=utf-8”);//设置返回值为json格式
response.getWriter().print(“attcat 解决乱码”);
处理GET 提交方法的servlet 中的doGet()方法
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get*************");
request.setCharacterEncoding("utf-8");
String attcat = request.getParameter("attcat");
//将接收来的二进制数据流以iso8859-1解码再转换成utf-8
attcat = new String(attcat.getBytes("iso8859-1"),"utf-8");
System.out.println(attcat);
//输出浏览器的格式
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.getWriter().print("attcat 解决乱码");
}
运行get
控制台输出
处理doPost提交方法的servlet 中的doPost()方法
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("进来post*************");
//解决post方法提交数据中的乱码问题
request.setCharacterEncoding("UTF-8");
String attcat = request.getParameter("attcat");
System.out.println(attcat);
//输出浏览器的格式
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.getWriter().print("attcat 解决乱码");
}