出现乱码的原因:浏览器端编码格式与服务器端编码格式不一样
字节流输出中文乱码
public class TestClass extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String outContent = "中文";
//获取响应输出流
ServletOutputStream sos = response.getOutputStream();
//设置浏览器端的编码
response.setHeader("Content-type", "text/html;charset=utf-8");
//也可以简写response.setContentType("text/html;charset=utf-8");
//设置服务端写出的格式
sos.write(outContent.getBytes("utf-8"));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
字符流输出中文乱码
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String outContent = "中文666!@#";
//设置服务端和客户端的编码形式
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.write(outContent);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
设置编码格式,尽量使用response.setContentType(“text/html;charset=utf-8”)方法,可以一步到位
常见支持中文的编码
GBK GB18030 GB2312,支持中文的编码,也支持其他一些字符
UTF-8万能码,支持所有字符