Spring MVC @ModelAttribute 参数乱码

issue
Spring MVC提交form表单后台通过@ModelAttribute获取参数为乱码
Spring MVC submit form and get random code parameters through `@ModelAttribute

Java Config WebInitializer

傻了,将CharacterEncodingFilter部分放到DispatcherServlet部分前面就可以了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class WebInitializer implements WebApplicationInitializer {

@Override
public void onStartup(javax.servlet.ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ApplicationConfig.class);
sc.addListener(new ContextLoaderListener(rootContext));

//CharacterEncodingFilter
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
FilterRegistration filterRegistration =
sc.addFilter("characterEncodingFilter", characterEncodingFilter);
filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");//注意这里匹配 "/*"

//follow can be deleted
//sc.addFilter("hibernateFilter", OpenSessionInViewFilter.class).addMappingForUrlPatterns(null, false, "/*");

//maybe follow will be use
// sc.addFilter("OpenEntityManagerInViewFilter", org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.class).addMappingForUrlPatterns(null, false, "/*");

//springmvc上下文
AnnotationConfigWebApplicationContext springMvcContext = new AnnotationConfigWebApplicationContext();
springMvcContext.register(MvcConfig.class);

//DispatcherServlet
DispatcherServlet dispatcherServlet = new DispatcherServlet(springMvcContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ServletRegistration.Dynamic dynamic = sc.addServlet("dispatcherServlet", dispatcherServlet);
dynamic.setLoadOnStartup(1);
dynamic.addMapping("/");


}
}