1. 程式人生 > 其它 >SpringMVC亂碼問題及json亂碼問題解決

SpringMVC亂碼問題及json亂碼問題解決

技術標籤:SpringMVC過濾器javaweb.xmlspring

下面展示一些 內聯程式碼片

在Web.xml中配置如下:

// An highlighted block
<!-- 配置springMVC編碼過濾器 -->
  <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> 在web.xml配置過濾器以後會將所有請求過濾,但是實際開發中有些靜態資源 不需要過濾,於是便要在springMVC-
servlet.xml配置檔案下配置靜態資源不過濾 springMVC-servlet.xml檔案中配置: <!-- location表示路徑,mapping表示檔案,**表示該目錄下的檔案以及子目錄的檔案 --> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/scripts/" mapping="/scripts/**"/> var foo = 'bar'; Jackson亂碼問題解決: 1.//produces:指定響應體返回型別和編碼 @RequestMapping(value = "/json1",produces = "application/json;charset=utf-8") 2.<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>