1.Servlet中用OutputStream输出数据以及输出中文
<span style="font-family:KaiTi_GB2312;font-size:14px;">public class ResponseOutputStreamCharset extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// OutputStream out = response.getOutputStream();
// out.write(1);//这个也是乱码,一定要注意out.write((1+"").getBytes());
// 1.程序以什么码表输出了,程序就一定要控制浏览器以什么码表打开
//还要注意的是在text/html和“;”之间不能有空格,否则浏览器将不能正确识别响应的内容类型。
response.setHeader("Content-type", "text/html;charset=utf-8");
// 2.response.setContentType("text/html;charset=utf-8");
String data = "中国";
OutputStream out = response.getOutputStream();
// 3.用html技术中的meta标签模拟了一个http响应头,来控制浏览器的行为
// out.write("<meta http-equiv='Content-type' content='text/html;charset=utf-8'>".getBytes());
out.write(data.getBytes("UTF-8"));
}
}
</span>
2.Servlet中用PrintWriter输出数据,输出中文的问题
<span style="font-family:KaiTi_GB2312;font-size:14px;">public class ResponseWriterCharset extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置response使用的码表,以控制response以什么码表向浏览器写数据
response.setCharacterEncoding("UTF-8");
//指定浏览器以什么码表打开服务器发送的数据
response.setHeader("Content-type", "text/html;charset=utf-8");
response.setContentType("text/html;charset=utf-8");
String data = "中国";
PrintWriter out = response.getWriter();
out.write(data);
}
}
</span>
3.Servlet中request乱码问题
request接受数据的乱码。比如前台页面是utf-8,但是到后台后,默认用iso-8859-1解析,自然不行。以前台编码为UTF-8为例
request.setCharacterEncoding("UTF-8");//只对post提交有效
new string(username.getBytes("iso-8859-1"),"UTF-8")//get提交乱码解决方式
<span style="font-family:KaiTi_GB2312;font-size:14px;">public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// POST
// 在获取用户表单信息之前把request的码表设置成UTF-8,
// request.setCharacterEncoding("UTF-8");
// String value = request.getParameter("username");
// System.out.println(value);
// GET
// 从request中获取客户端提交过来的中文信息,获取到乱码
String value = request.getParameter("username");
// 拿到乱码反向查找 iso-8859-1 码表,获取原始数据,在构造一个字符串让它去查找UTF-8码表得到正常数据
String value1 = new String(value.getBytes("iso-8859-1"), "UTF-8");
System.out.println(value1);
}</span>