关于乱码的解决方案

简介:

我们从两个方面入手,1 服务器对浏览器的响应 ,2 浏览器对服务器的请求

one by one

 1 服务器对浏览器的响应

让我们画图来说明这个复杂的问题吧,这样还能易于理解点。


好了,看完这个我相信你可以理解的很好了,我觉得我解释的够清楚了。

使用代码:

response.setHeader("Content-Type", "text/html;charset=utf-8");
		PrintWriter printWriter = response.getWriter();
		printWriter.println("你好,我用的是UTF-8");
		printWriter.close();

2浏览器对服务器的请求

一样我们还是来用图说话


怎么样,明白了吧,我们把解决的重点放在页面中点击表单或链接提交数据,而不去理会地址栏直接给参数,因为没有人这样做。

好了,让我们来看个案例吧:

<!DOCTYPE html>
<!-- 这是我们第一次请求是返回的表单 我们可以知道通过超链接或表单提交其参数编码为utf-8 -->
<html>
  <head>
    <title>MyHtml.html</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
  </head>
  
  <body>
    <form action="/day10/RequestEncodingTest" method="post"><!-- 通过post方法提交 -->
    	姓名:<input type="text" name="name"/>
    	密码:<input type="password" name="password">
    	<input type="submit" value="提交">
    </form>
    <a href="RequestEncodingTest?name=浩仔&password=123456">get方法</a><!-- 通过get方法提交 -->
  </body>
</html>
/**
 * 这个servlet用来接收表单或超链接的请求
 * @author 74087
 *
 */
public class RequestEncodingTest extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		byte[] names = name.getBytes("ISO-8859-1");//进行反编码得到字节数组
		byte[] passwords = password.getBytes("ISO-8859-1");
		name = new String(names,"UTF-8");//按照我们需要的编码方式进行编码
		password = new String(passwords,"UTF-8");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.println("name=" + name);
		pw.println("password=" + password);
		pw.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//设置编码方式
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.println("name=" + name);
		pw.println("password=" + password);
		pw.close();
		
	}

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值