数据库及页面乱码问题

目录

MySQL乱码问题

1、前台页面

2、控制器/过滤器(filter)

3、数据库及表格编码

4、字符流编码

5、Tomcat编码


MySQL乱码问题

1、前台页面

JSP、HTML页面头部设置字符编码为UTF-8。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

2、控制器/过滤器(filter)

(1)servlet设置页面请求和回应的编码:

request.setCharacterEncoding("utf-8");  [一般用于post请求方式]


response.setCharacterEncoding("utf-8"); 


(2)如果是struts2

struts.xml中添加如下语句:

<constant name="struts.i18n.encoding" value="utf-8" />


(3)如果使用了spring框架

web.xml配置中,设置初始化参数

<filter>
  <filter-name>yk</filter-name>
  <filter-class>com.servletlx.filter.YkFilter</filter-class>


  <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
  </init-param>


  </filter>


public class YkFilter implements Filter{

             //其他代码未全部写出,这里只写出和编码相关的语句

private String encoding = null;//定义表示编码方式的变量

@Override
             public void init(FilterConfig arg0) throws ServletException {
             // 获取初始化参数,只执行一次
            encoding = arg0.getInitParameter("encoding"); //获取参数的值,该值表示编码的方式
             }

 

           @Override
          public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {
                   //三个参数:请求,回应,过滤链
        HttpServletRequest request = (HttpServletRequest)arg0;
        HttpServletResponse response = (HttpServletResponse)arg1;
        request.setCharacterEncoding(encoding); //参数代表编码的方式
        response.setCharacterEncoding(encoding);

        .............

        }

 

}

3、数据库及表格编码

第一:保证数据库的编码方式为UTF-8;

第二:保证数据表的编码方式为UTF-8;

第三:使用jdbc连接数据库时,在URL中添加useUnicode参数(useUnicode=true表示使用Unicode字符集)和characterEncoding参数(characterEncoding=utf8,当useUnicode设置为true时,指定字符编码)

如:jdbc:mysql://localhost:3306/database_name?useUnicode=true&characterEncoding=utf8"

数据库及数据表的编码格式查看及修改请查看:MySQL相关命令

4、字符流编码

String string = request.getParametes('sname');

  //把得到的值转换为原始编码,再转换为UTF-8编码

  string=new String(string.getBytes("iso8859-1"),"UTF-8");  [一般用于get请求]

5、Tomcat编码

想通过get请求带中文数据也不会出现乱码,还需要编辑Tomcat的编码

 

server.xml文件中,在端口号8080后添加编码格式  URIEncoding=”utf-8”

 

    <Connector executor="tomcatThreadPool"

               port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443"  UTFEncoding=”utf-8” />

 

猜你喜欢

转载自blog.csdn.net/pro_fan/article/details/85332568