• Spring MVC+MySQL保存中文变成乱码


    环境:MySQL,Spring MVC3.2.0,jQuery v2.0.3,使用JdbcTemplate访问数据库,相当于全套Spring解决方案。

    现象

    直接使用表单POST,或者使用jQuery POST数据到服务端,在Controller中获得的中文字符串皆为乱码。到达JdbcTemplate插入或者更新数据库时,自然也是乱码。

    解决措施

    修改web.xml,增加编码过滤器,如下(注意,需要设置forceEncoding参数值为true)

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    效果

    在Controller中获得的中文字符串已正常。但使用JdbcTemplate插入或者更新数据库后,依然是乱码。可判定是写入数据库时,出现编码问题。

    解决措施

    修改applicationContext.xml文件,设置MySQL访问的url为:url="jdbc:mysql://localhost:3306/xxx?useUnicode=true&amp;characterEncoding=UTF-8"

    效果

    写入数据库也已经正常,读取和在网页上显示正常。

    参考

    http://blog.csdn.net/xuechongyang/article/details/8283924

    http://hi.baidu.com/fuzk2008/item/956351c17a47d653bcef6956

  • 相关阅读:
    Ajax配合Node搭建服务器,运用实例
    mapMutations m
    seaJS使用教程
    节流函数
    【Gin-API系列】Gin中间件之日志模块(四)
    【Gin-API系列】配置文件和数据库操作(三)
    【Gin-API系列】请求和响应参数的检查绑定(二)
    【Gin-API系列】需求设计和功能规划(一)
    【ansible】api 调用出现ssh交互式输入
    【ansible】api 调试
  • 原文地址:https://www.cnblogs.com/ygjlch/p/4020497.html
Copyright © 2020-2023  润新知