栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring + Hibernate + MySQL中文乱码问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring + Hibernate + MySQL中文乱码问题

文章目录
  • 概要
  • 问题
  • 解决
    • MySQL的配置连接
    • web.xml的配置
    • MySQL数据库配置
  • 参考

概要

在配置Spring + Hibernate存入MySQL数据库时有中文乱码的问题,尝试了解决办法。

问题

中文乱码解决起来有时会找不到头绪,必须要把各个配置都做正确才能解决,以下是几个注意点。

解决 MySQL的配置连接

在dispatcherServlet-servlet.xml里的设置尝试了多种配置,如下:

	
		
			com.mysql.jdbc.Driver
		
		
			jdbc:mysql://localhost:3306/myNews?useUnicode=true&characterEncoding=utf-8
			
			
			
		
		
			root
		
		
			P@ssw0rd
		
	
web.xml的配置

设置SetCharacterEncodingFilter方法

	
		setEncodingFilter
		com.SetCharacterEncodingFilter
		
			encoding
			
			
			utf-8 
		
	

SetCharacterEncodingFilter 实现 Filter

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {

        // Conditionally select and set the character encoding to be used
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null)
                request.setCharacterEncoding(encoding);
        }

	// Pass control on to the next filter
        chain.doFilter(request, response);

    }


    
    public void init(FilterConfig filterConfig) throws ServletException {

	this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null)
            this.ignore = true;
        else if (value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if (value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;

    }


    
    protected String selectEncoding(ServletRequest request) {

        return (this.encoding);

    }
MySQL数据库配置

my.ini里配置
character_set_server=utf8
并重启MySQL

MySQL数据库的整体Collation设置为utf8_bin
MySQL数据库的各中文字段设置Type为varchar,Collation设置为utf8_bin

参考

MysqlDataTruncation: Data truncation: Incorrect string value: ‘xF0x9Dx90xB6"#…’ for column
100% solution java.sql.SQLException : Unsupported character encoding ‘utf8mb4’.
史上最全的Spring MVC 中文乱码问题解决方案

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/678325.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号