有时候使用SpringMVC框架提交表单时会出现中文乱码,以下是我亲自试验过的配置字符过滤器的两种:
1、在web.xml中配置
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>orgspringframeworkwebfilterCharacterEncodingFilter</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>
2、JavaConfig
import javax.servlet.Filter; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class JavaSpringIn extends AbstractAnnotationConfigDispatcherServletInitializer { //配置字符过滤器 @Override protected Filter[] getServletFilters() { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); return new Filter[] {characterEncodingFilter}; } }