zoukankan      html  css  js  c++  java
  • 乱码问题锦记

    问题1:关response设置中文的乱码问题

    原因:response缓冲区的默认编码是iso8859-1,此码表中没有中文

    解决方法response.setContentType("text/html;charset=UTF-8");

    问题2:关于页面提交请求参数(request)出现的中文乱码的问题

    解决方法

        way1:    

          如果表单是用get提交方式,则需要在servlet中添加如下语句:

          request.setCharacterEncoding("UTF-8");

         如果表单使用post方式提交,则需要在servlet中添加如下语句:
         eg:以username为例:

            String username = request.getParameter("username");//此时username为乱码状态

            username = new String(username.getBytes("ISo-8859-1"),"UTF-8"); //此时username正常显示中文了

         原理

            

        way2:通过filter进行request.getParameter(name);的方法增强

           核心代码如下图所示:

          way3:通过代理对象将方法进行强化 

      public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        /**
        * 使用动态代理完成乱码问题
        */
        HttpServletRequest proxyInstance = (HttpServletRequest) Proxy.newProxyInstance(
          req.getClass().getClassLoader(),
          req.getClass().getInterface(),
          new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
              throws Throwable {
              if("getParameter".equals(method.getName())){
                String invoke = (String) method.invoke(req, args);//乱码
                invoke = new String(invoke.getBytes("ISO-8859-1"), "UTF-8");
                return invoke;
              }    
              return method.invoke(req, args);
            }
          });
          chain.doFilter(proxyInstance, resp);
         }

      

    问题3:cookie不能保存中文。那么如何将cookie中的中文进行保存?

    解决方法在将中文字符username保存到cookie中,首先将username进行编码,URLEncoder.encode(username, "UTF-8");此时得到的是一串字符串,记为cookie_username,保存到cookie中。然后,我们从cookie中取到cookie_name这串乱码,对它进行解析,URLDecoder.decode(cookie_name, "UTF-8");此时得到的就是一串中文字符。

    问题4:     

  • 相关阅读:
    Linux命令: 向文件写内容,编辑文件,保存文件,查看文件,不保存文件
    SQL: 左连接,右连接,内连接,左外连接,右外连接,完全连接
    Python: 没有switch-case语句
    Python:键盘输入input
    Python: 猴子分桃。海滩上有一堆桃子,五只猴子来分。
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
    Scrapy安装
    Linux: 回到根目录cd /
    怎么查看是否安装Scrapy
    虚拟环境Scrapy安装
  • 原文地址:https://www.cnblogs.com/empcl1314/p/6947698.html
Copyright © 2011-2022 走看看