Response对象通过字节流输出中文内容

Response对象通过字节流输出中文内容:

第一种方法:

ResponseDemo1.java文件:

package com.neu;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(response);
	}

	//解决方案一:更改浏览器的码表(不建议)
	//解决方案二(不建议):向客户端输出一个<meta>标签,模拟了响应消息头:<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>
	//解决方案三(建议):向客户端输出响应消息头:response.setHeader("Content-Type", "text/html;charset=UTF-8");
	//解决方案四(建议):向客户端输出响应消息头response.setContentType("text/html;charset=UTF-8");
	//字节流输出数据查UTF-8
	private void test2(HttpServletResponse response) throws IOException{
		String data = "不见了远处的青山";
		response.setContentType("text/html;charset=UTF-8");
		ServletOutputStream out = response.getOutputStream();
		out.write(data.getBytes("UTF-8"));//默认情况下:浏览器是乱码的(他默认查GBK)
	}
	
	//字节流输出数据查本地码表
	private void test1(HttpServletResponse response) throws IOException {
		String data = "不见了远处的青山";
		ServletOutputStream out = response.getOutputStream();
		out.write(data.getBytes());//String:  getBytes()查本地默认的码表GBK getBytes(String charset)查指定码表
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
运行:http:localhost:8080/Response/servlet/ResponseDemo1

结果:不见了远处的青山

第二种方法:

ResponseDemo2.java文件:

运行:http:localhost:8080/Response/servlet/ResponseDemo1

package com.neu;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 字符流输出中文数据
 * @author wym
 *
 */
public class ResponseDemo2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		test1(response);
	}

	private void test1(HttpServletResponse response) throws IOException {
		String data = "幸福是什么?";
		//改变字符流查的码表
		response.setCharacterEncoding("UTF-8");
		//告知客户端用UTF-8进行解码
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();//HttpServletResponse的实例由Tomcat服务器提供,Tomcat6.x默认查ISO-8859-1编码;Tomcat8.x默认编码为UTF-8
		out.write(data);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

运行:http:localhost:8080/Response/servlet/ResponseDemo2

结果:幸福是什么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值