关于乱码的解决方案

来源:互联网 发布:网络大电影如何挣钱 编辑:程序博客网 时间:2024/05/16 09:27

简介:

我们从两个方面入手,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 0