request和response中文乱码问题

来源:互联网 发布:mac无法解压zip 编辑:程序博客网 时间:2024/05/06 03:57
response乱码
1 使用字节流向页面输出
* 1、设置浏览器的编码
* 2、设置字节数组的编码
* 让浏览器的编码和字节数组的编码一致


// <meta http-equiv="content-type" content="text/html; charset=UTF-8">
response.setHeader("content-type", "text/html; charset=UTF-8");
response.getOutputStream().write(" 使用字节流向页面输出内容".getBytes("UTF-8"));

2 使用字符流向页面输出
* 解决方法:
* 1、设置response缓冲区的编码
* 2、设置浏览器的编码
* response缓冲区的编码和浏览器的编码一致


response.setCharacterEncoding("UTF-8");
// <meta http-equiv="content-type" content="text/html; charset=UTF-8">
response.setHeader("content-type", "text/html; charset=UTF-8");
response.getWriter().write(" 使用字符流向页面输出内容");


字符流向页面输出中文乱码问题解决,简写方式
// <meta http-equiv="content-type" content="text/html; charset=UTF-8">
reesponse.setContentType("text/html; charset=UTF-8");
response.getWriter().write("简写 ,使用字符流向页面输出内容");




request中表单提交的中文数据乱码问题的解决
   <body>
    <a href="javascript:void(0);" onclick="click1();">中文传递数据</a>
  </body>
  
  <script type="text/javascript">
  function click1(){
  var name="你好";
  location.href="/day08_my/rdemo05?name="+encodeURI(encodeURI(name));
  }
  </script>
(1)post提交方式解决方法,会有一个缓冲区
/*
* (1)post提交方式解决方法
*/
//方法一
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String decode = URLDecoder.decode(request.getParameter("name"), "UTF-8");
System.out.println(decode);
}

//方法二
private void test1(HttpServletRequest request)
throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");//会有一个缓冲区
System.out.println(request.getParameter("login"));
System.out.println(request.getParameter("password"));
}


(2)get提交中文乱码解决
改tomcat服务器
   <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="utf-8"/>


/*
* (2)get提交中文乱码解决
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String login = request.getParameter("login");
login = new String(login.getBytes("iso8859-1"),"utf-8");
System.out.println(login);
}
0 0
原创粉丝点击