总共要设置三处编码:
1、 数据库编码统一设置utf8
2、在web.xml设置编码, 增加编码过滤器:
<filter>如果没有设置这个的话, 那么表单的值传给Controller的时候, 就已经乱码了
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、在spring-servlet.xml 设置编码, 在数据库url地址后面加入 ?useUnicode=true&characterEncoding=utf-8。
如下: <bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>