springMVC返回漢字字符串亂碼,以及返回的字符串亂碼的問題


1、springMVC在使用@ResponseBody注解返回字符串為什么出現亂碼呢?(這里以spring4.3.1為例)

原因分析:原因在返回字符串時StringHttpMessageConverter默認編碼為:ISO8859-1,如下:

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
    public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
    private final List<Charset> availableCharsets;
    private boolean writeAcceptCharset = true;
    /**
     * A default constructor that uses {@code "ISO-8859-1"} as the default charset.
     * @see #StringHttpMessageConverter(Charset)
     */
    public StringHttpMessageConverter() {
        this(DEFAULT_CHARSET);
    }
    /**
     * A constructor accepting a default charset to use if the requested content
     * type does not specify one.
     */
    public StringHttpMessageConverter(Charset defaultCharset) {
        super(defaultCharset, MediaType.TEXT_PLAIN, MediaType.ALL);
        this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
    }
  //.........以下省略
}

找到問題之后,可以從以下幾種方式解決亂碼問題:

方式一、在springMVC配置文件中修改StringHttpMessageConverter的默認編碼:(已經驗證有效)

 

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <!-- spring消息轉換器:如果要動用這些消息轉換器,需要在特定的位置加上@RequestBody或者@ResponseBody -->
        <property name="messageConverters">  
             <list>
                 <!-- 作用:String類型解析器,允許直接返回String類型的消息 -->
                <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
                    <!-- constructor-arg配置可作為以后擴展了解 -->
                    <!-- <constructor-arg value="UTF-8" index="0"/> -->
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/plain;charset=UTF-8</value>
                            <!-- 注意:用以下時不會起作用 -->
                            <!-- <value>text/html;charset=UTF-8</value> -->
                        </list>
                    </property>
                </bean>
            </list>  
        </property>
    </bean>

 

方式二、直接在springMVC配置文件中直接配置<mvc:annotation-driven />,在對應的方法上如下:

    @RequestMapping(value="beanParameter",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String getPamaterbyEntity(Employee employee){
    System.out.println("empName:"+employee.getEmpName()+",salary:"+employee.getSalary()); ModelAndView modelAndView = new ModelAndView(); return employee.getEmpName(); }

方式三、未驗證

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="stringHttpMessageConverter"/>
            <ref bean="jackson2HttpMessageConverter"/>
        </list>
    </property>
</bean>

<mvc:annotation-driven />

注意:配置必須在 <mvc:annotation-driven /> 之前,否則將不會啟效;<mvc:annotation-driven /> 會自動注冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter。

方式四、直接使用json解析器(未驗證)

<!-- 返回json  需要導入jackson-core-2.4.1.jar,jackson-databind-2.4.1.jar,jackson-annotations-2.4.0.jar-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <!-- 避免IE執行AJAX時,返回JSON出現下載文件 -->
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 這里順序不能反,一定先寫text/html,不然ie下出現下載提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

注意:使用@responsebody注解並且返回值類型為String時,返回的string字符串帶有雙引號,其原因是直接將string類型轉成了json字符串,

應該在json解析器之前添加字符串解析器

<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM