為了防止前端傳入的中文數據出現亂碼問題,使用Spring提供的編碼過濾器來統一編碼。
要使用編碼過濾器,只需要在web.xml中添加如下代碼:
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
另一個一定會配置的是ViewResolver視圖解析器,將方法中所定義的View路徑簡化。
要使用視圖解析器,只需要在springmvc-config.xml中添加如下代碼:
<!-- 定義視圖解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 設置前綴 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 設置后綴 -->
<property name="suffix" value=".jsp"></property>
</bean>
