zoukankan      html  css  js  c++  java
  • Spring MVC —— form表单post提交出现乱码

    主要原因是:页面提交时,使用<contentType:utf-8/>格式,而服务端HttpMessageConverter解码时使用其它格式解码(如:ISO-8859-1)导致

    解决方案:在Servlet中设置CharacterEncoding为UTF-8格式。

    方法一:在Web.xml中加入Spring的字符集过滤器(已测)

    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    encoding

    字符集,将request字符集设置成encoding指定格式(相当于request.setCharacterEncoding)

    forceEncoding

    强制字符集设置,主要用来设置response字符集是否也是encoding指定格式

    当设置为true时,相当于request.setCharacterEncoding + response.setCharacterEncoding

    当设置为false时(默认),相当于request.setCharacterEncoding

    加入后相当于在servlet中加入下面代码

    request.setCharacterEncoding("UTF-8");    
    response.setCharacterEncoding("UTF-8"); 

    方法二:手动写Filter(未测)

    对每个访问进行拦截,并执行下列代码

    request.setCharacterEncoding("UTF-8");    
    response.setCharacterEncoding("UTF-8"); 

    方法三:设置HttpMessageConverter实现类的解码方式(未测试)

    <mvc:annotation-driven>    
        <mvc:message-converters>    
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">    
                <property name="supportedMediaTypes">    
                    <list>    
                        <value>text/plain;charset=UTF-8</value>    
                        <value>text/html;charset=UTF-8</value>    
                    </list>    
                </property>    
            </bean>    
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
                <property name="supportedMediaTypes">    
                    <list>    
                        <value>application/json; charset=UTF-8</value>    
                        <value>application/x-www-form-urlencoded; charset=UTF-8</value>    
                    </list>    
                </property>    
            </bean>    
        </mvc:message-converters>    
    </mvc:annotation-driven>
  • 相关阅读:
    最长上升子序列(实验回顾)
    数据库应用开发一、vs
    全文检索
    mangtomant 增删改查
    django
    SQLAlchemy 增删改查 一对多 多对多
    Flask-Sqlalchemy—常用字段类型说明
    flask
    文件下载
    python连接mongodb
  • 原文地址:https://www.cnblogs.com/yifanSJ/p/9226801.html
Copyright © 2011-2022 走看看