• 向数据库插入中文乱码


    又遇到乱码问题,这个编码问题有时候真是让人头大。找了半天都找不出来哪里出了问题,页面和数据库均是使用utf8编码,但是还是出现了乱码。直接在命令行下向数据库插入中文数据时不会出现乱码,在程序中使用代码插入时会出现乱码,控制台中打印出来数据没有乱码,没搞清楚哪里出了问题。通过查找资料最终将乱码问题解决,但是还有些不明白问题出在哪里。

    通过在数据库连接url中加入?useUnicode=true&characterEncoding=UTF-8解决问题:

    applicationContext.xml

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/cms?useUnicode=true&characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="" />
    
    </bean>

    我的处理编码的filter:

    public class EncodingFilter implements Filter {
    
        private FilterConfig config;
        private String charset = "UTF-8";
    
        public void init(FilterConfig filterconfig) throws ServletException {
            config = filterconfig;
            String s = config.getInitParameter("encoding");
            if (s != null) {
                charset = s;
            }
        }
    
        public void destroy() {
            config = null;
        }
    
        public void doFilter(ServletRequest servletrequest,
                ServletResponse servletresponse, FilterChain filterchain)
                throws IOException, ServletException {
            
            servletrequest.setCharacterEncoding(charset);
            servletresponse.setCharacterEncoding(charset);
            
            filterchain.doFilter(servletrequest,servletresponse);
        }
    
    }

    经测试filter确实被执行了。

    数据库是使用utf8编码:

    jsp页面和所有Java文件都是使用的utf8编码。
    没看出问题具体出现在哪一点,目前有点赶时间,先把问题解决了,有时间的好好研究一下这个编码问题。遇到很多次了,还不能小看这个编码问题。上次在程序中使用utf8编码的url地址访问windows服务器上的资源文件,出现404,改用gbk就能够访问了。还有一次发现页面在低版本chrome下出现部分css失效的问题,但是在ie和高版本的chrome中又没问题,当时还以为是css兼容性问题,后来发现失效的部分正是css文件中出现中文注释之后的样式,将中文注释去掉,则能够正常显示了。将css文件编码改为和页面编码相同(utf8)问题就解决了。还有页面之间中文参数传递时的编码和解码问题,搞web开发跟编码打交道的时间真多,有时候稍不注意就弄出乱码了。

  • 相关阅读:
    NSString属性声明中的copy和retain区别
    Xcode6无法安装VVDocumenter插件的解决方法
    Xcode好用插件
    REVEAL APP for IOS 永久试用
    Foundation框架 ---- 结构体
    Foundation框架集合 ---- NSArray和NSMutableArray
    《 算法分析与设计》 实验一-分治算法
    B-浮点常量问题
    Servlet 404原因
    小C语言--词法分析程序
  • 原文地址:https://www.cnblogs.com/jdluojing/p/3212420.html
Copyright © 2020-2023  润新知