向页面输出中文(乱码问题)
字节:ServletOutputStream getOutputStream() 字节输出流
* 字节的输出中文的乱码
* * 输出哈罗我的是否乱码呢?
* * 不一定乱码。
* * 解决办法
* * 设置浏览器打开文件时所采用的编码
* response.setHeader("Content-Type", "text/html;charset=UTF-8");
* * 获取字符串byte数组时编码和打开文件时编码一致。
* "哈罗我的".getBytes("UTF-8")
PrintWriter getWriter() 字符输出流
* 字符输出中文是否乱码呢?
* * 肯定乱码
* response缓冲区的编码,默认值ISO-8859-1
* * 设置response缓冲编码
* response.setCharacterEncoding("UTF-8");
* * 设置浏览器打开文件所采用的编码
* response.setHeader("Content-Type", "text/html;charset=UTF-8");
* * 简写方式
* response.setContentType("text/html;charset=UTF-8");
* 总结:response对象输出中文,产生乱码。
* 字节
* 解决方案
* 设置浏览器打开文件时采用的编码
response.setHeader("Content-Type", "text/html;charset=UTF-8");
* 获取字符串的byte数组采用的编码
"哈罗我的".getBytes("UTF-8")
* 字符
* 解决方法
* 设置浏览器打开文件时采用的编码
response.setHeader("Content-Type", "text/html;charset=UTF-8");
* 设置response缓冲区的编码
response.setCharacterEncoding("UTF-8");
* 简写的方式(等于上面的两句)
* response.setContentType("text/html;charset=UTF-8");
response开发细节
向客户端输出字符中文的简写方式
response.setContentType("text/html;charset=UTF-8");
package cn.learn.response;
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;
/**
* 输出中文的乱码的问题
* @author Administrator
*
*/
public class OutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
run2(response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* 字符输出中文是否乱码呢?
* * 肯定乱码
* response缓冲区的编码,默认值ISO-8859-1
* * 设置response缓冲编码
* response.setCharacterEncoding("UTF-8");
* * 设置浏览器打开文件所采用的编码
* response.setHeader("Content-Type", "text/html;charset=UTF-8");
* * 简写方式
* response.setContentType("text/html;charset=UTF-8");
*
* @param response
* @throws IOException
*/
public void run2(HttpServletResponse response) throws IOException{
// 设置response缓冲区的编码
//response.setCharacterEncoding("UTF-8");
// 设置浏览器打开文件所采用的编码
//response.setHeader("Content-Type", "text/html;charset=UTF-8");
// 简写的形式(等于上面两句)
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("哈罗卧得");
}
/**
* 字节的输出中文的乱码
* * 输出哈罗我的是否乱码呢?
* * 不一定乱码。
* * 解决办法
* * 设置浏览器打开文件时所采用的编码
* response.setHeader("Content-Type", "text/html;charset=UTF-8");
* * 获取字符串byte数组时编码和打开文件时编码一致。
* "哈罗我的".getBytes("UTF-8")
* @throws IOException
*/
public void run1(HttpServletResponse response) throws IOException{
// 设置浏览器打开文件时编码
response.setHeader("Content-Type", "text/html;charset=UTF-8");
// 获取字节输出流
OutputStream os = response.getOutputStream();
// 输出中文
os.write("哈罗我的".getBytes("UTF-8"));
}
}
本文详细解析了在Servlet中输出中文时遇到的乱码问题,包括字节流和字符流的处理方式,以及如何通过设置编码来避免乱码,提供了具体的代码示例。
2169

被折叠的 条评论
为什么被折叠?



