I know struts2 default config will trim all strings obtained from forms.
For example:
I type
" whatever "in a form and submit, I will get
"whatever"The string has been auto trimmed
Does spring mvc have this function too? THX.
View: Spring MVC form tags are used to render the equivalent HTML form fields, and most importantly, bind the object in the model with the form. Controller: alongside with handling requests, the controller binds the model object with the view and vice-versa, and delegates processing to dedicated business/service class.
Overview. One of the most important Spring MVC annotations is the @ModelAttribute annotation. @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view.
Spring MVC is a Model-View-Controller(MVC) web framework build on notion of a central Front Controller servlet (DispatherServlet) which is responsible for dispatching each request to appropriate handlers, resolving views and finally returning the response.
Using Spring 3.2 or greater:
@ControllerAdvice public class ControllerSetup { @InitBinder public void initBinder ( WebDataBinder binder ) { StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true); binder.registerCustomEditor(String.class, stringtrimmer); } }
Testing with an MVC test context:
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration public 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(); } } } /** * we are testing trimming of strings with it. * * @author janning * */ @Controller class TestController { @RequestMapping("/test") public String test ( String test ) { return test; } }
And - as asked by LppEdd - it works with passwords too as on the server side there is no difference between input[type=password] and input[type=text]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With