zoukankan      html  css  js  c++  java
  • 注意语句顺序 防止Servlet Request Response乱码

      

    servlet乱码一般分为Request发生乱码和Response发生乱码

    对于Request发生乱码一般是由于tomcat容器的默认编码是ISO-8859-1

    而Java中的编码是UTF-8的,因此可以对

    String myparam=request.getParameter("myparam");

    得到的参数进行编码转化

    myparam = new String(myparam.getBytes("ISO-8859-1"),"UTF-8");

    对于Response发生乱码是由于页面不知道发送来的数据的编码格式

    一般可以使用:

    response.setCharacterEncoding("utf8");

    注意这一句一定要在

    PrintWriter out=response.getWriter();

    获得输出对象之前,否则编码的设置将不能对输出流生效,也就发生乱码了

    网上有很多解决乱码的文章和方法.但很少有提到要注意这个语句顺序的

    这是实验验证的结论,而且从逻辑上也是说的通的.

    写作则能避免乱码:

           response.setCharacterEncoding("utf8");

           PrintWriter out=response.getWriter();

    写作

           PrintWriter out=response.getWriter();

           response.setCharacterEncoding("utf8");

    则是无效的设置,不能解决乱码.

     

     一个消除乱码的demo代码:

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

           String myparam=request.getParameter("myparam");

           myparam = new String(myparam.getBytes("ISO-8859-1"),"UTF-8");

          

           response.setCharacterEncoding("utf8");

           response.setContentType("text/html");

           PrintWriter out=response.getWriter();

          

           out.write("汉字");

        }

     

  • 相关阅读:
    POJ 2823 Sliding Window & Luogu P1886 滑动窗口
    Luogu P2970 [USACO09DEC]自私的放牧
    Luogu P2922 秘密消息
    Luogu P3353 在你窗外闪耀的星星
    Luogu P2580 于是他错误的点名开始了
    Floyd详解
    高精度模板
    51Nod P1100 斜率最大
    洛谷——P1025 数的划分
    洛谷——P1063 能量项链
  • 原文地址:https://www.cnblogs.com/oyjj/p/2132941.html
Copyright © 2011-2022 走看看