Spring MVC可以修剪从表单获取的所有字符串吗?


问题内容

我知道struts2的默认配置会修剪从表单获取的所有字符串。

例如:

我输入

“ 随你 ”

表格并提交,我会得到

“随你”

字符串已自动修剪

spring mvc是否也具有此功能?谢谢。


问题答案:

使用Spring 3.2或更高版本:

@ControllerAdvice
public class ControllerSetup
{
    @InitBinder
    public void initBinder ( WebDataBinder binder )
    {
        StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true);
        binder.registerCustomEditor(String.class, stringtrimmer);
    }
}

使用MVC测试环境进行测试:

@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;
    }
}

而且-正如LppEdd所要求的-它也可以使用密码,因为在服务器端,input [type = password]和input [type =
text]之间没有区别