Servlet之Request&Response的编码问题

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>


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值