zoukankan      html  css  js  c++  java
  • get与post中文乱码问题

    Jsp默认的字符编码格式是iso-8859-1

    因为post方法与get方法传递参数的方式不一样,所以有不同的解决方法。

    一、post乱码解决方法:
     1.设置请求和响应的编码方式
     //设置请求的编码格式
     request.setCharacterEncoding("UTF-8");
     //设置响应的编码格式
     response.setCharacterEncoding("UTF-8");
     或者
     <%@page language="java" contentType="text/html;charset=utf-8"%>

    post中文乱码还可以设置filter过滤器,直接使用代码就可以,最后要去web.xml中配置

    public class CharacterEncoding implements Filter {
    
        @Override
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            //这是post中文乱码的处理方式,get中文处理方式是在tomcat中配置
            //设置字符编码
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            //注意这句一定要有,作用是将请求转发给过滤器链上下一个对象
            //filter链
            chain.doFilter(request, response);
            //然后还要去web.xml中配置
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    
    }

    filter在web.xml中的配置代码 

     <filter>
          <filter-name>CharacterEncoding</filter-name>
          <filter-class>filter.CharacterEncoding</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>CharacterEncoding</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>

    二、get乱码解决方法:
     1.治标方法
     //先获取登录页面username的数据
     String username=request.getParameter("username");
     //将username字符编码改为utf-8
     String un=new String(username.getBytes("iso-8859-1"),"utf-8");
     //然后打印输出un
     out.print(un);

     2.治本方法
     在Tomcat安装目录下找到server.xml文件找到下面代码添加 URIEncoding="UTF-8"
     D:Program Filesapache-tomcat-8.0.33apache-tomcat-8.0.33confserver.xml
       <Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443"  URIEncoding="UTF-8"/>

     或者
     添加  useBodyEncodingForURI="true"
     <Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443"  useBodyEncodingForURI="true"/>

    ---------------------------------------------------------------------------------------------------------------

    在datebase.properties配置文件中 加入下面这句代码

    可以避免中文输入到数据库产生乱码的情况

    url=jdbc:mysql://127.0.0.1:3306/news?useUnicode=true&characterEncoding=utf-8

  • 相关阅读:
    IOS中的国际化的使用(Xcode 6.0之后的使用步骤)
    KVC,KVO的区别和使用
    通知,代理,block 单例的使用和区别
    NSoperation的使用
    多线程之Nsthread的使用方法
    多线程的之GCD的介绍
    IOS中生成证书、真机调试、上线发布程序的步骤
    IOS之NavigationController跳转到指点的界面
    IOS之截取字符串的使用方法
    ios 之定时器的使用的技巧(结合runloop)使用
  • 原文地址:https://www.cnblogs.com/fifiyong/p/5930535.html
Copyright © 2011-2022 走看看