您的位置:首页 > 其它

response实现案例之向页面输出中文解决乱码问题

2016-01-28 22:00 441 查看

1.向页面输出中文(乱码问题)

1.1字节:

ServletOutputStream getOutputStream() 字节输出流

* 字节的输出中文的乱码

* * 输出哈罗我的是否乱码呢?

* * 不一定乱码。

* * 解决办法:

* 1* 设置浏览器打开文件时所采用的编码

* response.setHeader("Content-Type", "text/html;charset=UTF-8");

* 2* 获取字符串byte数组时编码和打开文件时编码一致。

* "哈罗我的".getBytes("UTF-8")

1.2.字符

PrintWriter getWriter() 字符输出流

* 字符输出中文是否乱码呢?

* * 肯定乱码

* response缓冲区的编码,默认值ISO-8859-1

* 1.* 设置response缓冲编码

* response.setCharacterEncoding("UTF-8");

* 2.* 设置浏览器打开文件所采用的编码

* response.setHeader("Content-Type", "text/html;charset=UTF-8");

* * 上面两步的简写方式:

* response.setContentType("text/html;charset=UTF-8");


2.总结:response对象输出中文,产生乱码。

2.1 * 字节

* 解决方案

* 设置浏览器打开文件时采用的编码

response.setHeader("Content-Type", "text/html;charset=UTF-8");

* 获取字符串的byte数组采用的编码

"哈罗我的".getBytes("UTF-8");

2.2 * 字符

* 解决方法

* 设置浏览器打开文件时采用的编码

response.setHeader("Content-Type", "text/html;charset=UTF-8");

* 设置response缓冲区的编码

response.setCharacterEncoding("UTF-8");

* 简写的方式(等于上面的两句)

* response.setContentType("text/html;charset=UTF-8");

package cn.itcast.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);
}

/**
* 字节的中文乱码问题
* 	不一定乱码
* @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"));
}

/**
* 字符的中文乱码问题
*  肯定乱码
*  	response缓冲区的编码,默认是ISO-8859-1
*  设置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("哈喽沃德时节");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: