当前位置: 代码迷 >> 综合 >> servlet PrintWriter out = response.getWriter() out.write() 中文乱码
  详细解决方案

servlet PrintWriter out = response.getWriter() out.write() 中文乱码

热度:76   发布时间:2024-02-10 00:46:33.0

servlet PrintWriter out = response.getWriter() out.write() 中文乱码

本文系作者经验总结。作者邮箱:547317812@qq.com

一、问题描述

在使用Servlet通过out.write()回写数据时,如果字符串中含有中文,会出现中文乱码的问题。

二、解决办法

Servletpostget方法中,方法开始就加入3行代码:

request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");

举例:

@WebServlet("/ajax/test.do")
public class AjaxServlet extends javax.servlet.http.HttpServlet {protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");response.setCharacterEncoding("utf-8");User user = new User();user.setId(1);user.setUserName("547317812@qq.com");user.setPassword("123456");user.setNickName("哪吒");user.setEmployer("天庭");user.setPosition("中坛元帅");RespBody respBody = new RespBody();respBody.setCode(0);respBody.setMsg("请求成功");respBody.setData(user);String respJSON = JSON.toJSONString(respBody);response.getWriter().write(respJSON);}protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {this.doPost(request, response);}
}

问题可破!

  相关解决方案