使用Spring 3.2或更高版本:
@ControllerAdvicepublic class ControllerSetup{ @InitBinder public void initBinder ( WebDataBinder binder ) { StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true); binder.registerCustomEditor(String.class, stringtrimmer); }}使用MVC测试环境进行测试:
@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfigurationpublic class ControllerSetupTest{ @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup ( ) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void stringFormatting ( ) throws Exception { MockHttpServletRequestBuilder post = post("/test"); // this should be trimmed, but only start and end of string post.param("test", " Hallo Welt "); ResultActions result = mockMvc.perform(post); result.andExpect(view().name("Hallo Welt")); } @Configuration @EnableWebMvc static class Config { @Bean TestController testController ( ) { return new TestController(); } @Bean ControllerSetup controllerSetup ( ) { return new ControllerSetup(); } }}@Controllerclass TestController{ @RequestMapping("/test") public String test ( String test ) { return test; }}而且-正如LppEdd所要求的-它也可以使用密码,因为在服务器端,input [type = password]和input [type =
text]之间没有区别



