• 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

  • 相关阅读:
    vss的ss.ini丢失或损坏导致的vss无法登录错误
    NHibernate各种数据库连接参数文件配置方法说明
    oracle操作语句
    企业微信群聊机器人发送本地图片
    securecrt 或xshell 转发80端口
    SecureCRT 或 XSHELL 转发 X11 图形化GUI
    Windows 创建 .gdbinit 提示必须键入文件名
    vscode C++ 程序 windows
    vscode C++ 程序 windows
    解决source insight 4.0 不识别.cc文件的问题
  • 原文地址:https://www.cnblogs.com/fifiyong/p/5930535.html
Copyright © 2020-2023  润新知