OutputStream输出中文数据乱码问题解决方式:
package cn.lsh.servlet;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Response的OutputStream输出中文数据问题
public class Response extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定以UTF-8编码,那么就要指定浏览器以UTF-8解码,总之,编码与解码要相同,否者就会出现乱码。
//注意:第二个参数中间不要写成“,”否则当访问Servlet时会出现提示下载的情况。
response.setHeader("content-type", "text/html;charset=utf-8");
String str = "中国,我爱你";
OutputStream out = response.getOutputStream();
out.write(str.getBytes("utf-8"));//指定以UTF-8编码。
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Writer输出数据乱码的问题解决方法:
以下是没有指定浏览以UTF-8码表打开所以导致浏览器输出乱码:
package cn.lsh.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Response的OutputStream输出中文数据问题
public class Response extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定以UTF-8编码,那么就要指定浏览器以UTF-8解码,总之,编码与解码要相同,否者就会出现乱码。
//注意:第二个参数中间不要写成“,”否则当访问Servlet时会出现提示下载的情况。
//设置response使用utf-8码表,以控制response以什么码表向浏览器写出数据
response.setCharacterEncoding("UTF-8");
/*
//指定浏览器以什么码表打开服务器发送的数据
response.setContentType("text/html;charset=utf-8");
*/
String str = "中国,我爱你";
PrintWriter pw = response.getWriter();
pw.write(str);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}浏览器输出结果为:
以下指定浏览以UTF-8码表打开所以浏览器输出中文数据正常:
package cn.lsh.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Response的OutputStream输出中文数据问题
public class Response extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定以UTF-8编码,那么就要指定浏览器以UTF-8解码,总之,编码与解码要相同,否者就会出现乱码。
//注意:第二个参数中间不要写成“,”否则当访问Servlet时会出现提示下载的情况。
//设置response使用utf-8码表,以控制response以什么码表向浏览器写出数据
response.setCharacterEncoding("UTF-8");
//指定浏览器以什么码表打开服务器发送的数据
response.setContentType("text/html;charset=utf-8");
String str = "中国,我爱你";
PrintWriter pw = response.getWriter();
pw.write(str);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
输出结果正常: