JavaWeb乱码修正

package cn.ITHong.Response;


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 ResponseDemo2 extends HttpServlet {


	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test5(response);
	}
	/**
	 *作用于下面相同,推荐这种方法*/
	private void test5(HttpServletResponse response) throws IOException {
		//以字节流向客户端输出中文数据
		String s = "学人要学";
		ServletOutputStream out = response.getOutputStream();
		response.setContentType("text/html;charset=UTF-8");
		out.write(s.getBytes("UTF-8"));
	}
	/**
	 *标签提示客户端,未能实现,直接把第一个write直接输出到浏览器了,暂时用
	 *test3(),目的是一样的*/
	private void test4(HttpServletResponse response) throws IOException {
		//以字节流向客户端输出中文数据
		String s = "与内心相连";
		ServletOutputStream out = response.getOutputStream();
		out.write("<meta http-equiv='Content-Type'content='text/html;charset=UTF-8'>".getBytes());
		out.write(s.getBytes("UTF-8"));
	}
	/**
	 *给与响应头,解决浏览器乱码*/
	private void test3(HttpServletResponse response) throws IOException {
		//以字节流向客户端输出中文数据
		String s = "幸福与贫富无关";
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		ServletOutputStream out = response.getOutputStream();
		out.write(s.getBytes("UTF-8"));
	}
	/**
	 *乱码:因为我传输的是UTF-8,但是客户端却是GBK*/
	private void test2(HttpServletResponse response) throws IOException {
		//以字节流向客户端输出中文数据
		String s = "幸福与贫富无关";
		ServletOutputStream out = response.getOutputStream();
		out.write(s.getBytes("UTF-8"));
	}
	/**
	 * getBytes();使用平台默认的字符集GBK将此String解码为字节序列。
	 * 并将结果存储到一个新的字节数组中,但是外国人就不一定解析GBK了
	 * 没有乱码*/
	private void test1(HttpServletResponse response) throws IOException {
		//以字节流向客户端输出中文数据
		String s = "幸福是什么";
		ServletOutputStream out = response.getOutputStream();
		out.write(s.getBytes());
	}


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


	
	}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值