可以弹簧mvc修剪从表格中获得的所有琴弦吗?

Gor*_*uan 31 spring spring-mvc

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

例如:

我打字

"   whatever "
在表格和提交,我会得到
"whatever"
该字符串已被自动修剪

spring mvc也有这个功能吗?谢谢.

Jan*_*ing 41

使用Spring 3.2或更高版本:

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

使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且 - 正如LppEdd所要求的那样 - 它也适用于密码,因为在服务器端,输入[type = password]和输入[type = text]之间没有区别

  • 这是 Spring 3.2 或更高版本的最佳答案,尽管测试代码分散了它的简单性。您只需要第一个代码块。代码的其余部分并不特定于该问题。您也可以直接将其放入控制器类或控制器的基类中,而不是将其放入 *ControllerAdvice* 类中。 (2认同)

小智 11

注册此属性编辑器: org.springframework.beans.propertyeditors.StringTrimmerEditor

AnnotionHandlerAdapter的示例:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  ...
  <property name="webBindingInitializer">
    <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
      <property name="propertyEditorRegistrar">
         <bean class="org.springframework.beans.propertyeditors.StringTrimmerEditor" />
      </property>
    </bean>
  </property>
  ...
</bean>
Run Code Online (Sandbox Code Playgroud)

  • 我不确定你们是如何设法使它工作的,但在Spring Portlet MVC中,这根本不会让步.首先,StringTrimmerEditor没有实现PropertyEditorRegistrar接口,即使它没有,它也没有默认的no-arg构造函数.我最后编写了自己的StringTrimmerEditorRegistrar并注入ConfigurableWebBindingInitializer,但我很想知道每个人是如何设法让它工作的? (2认同)
  • 如果您使用的是Spring 3.2或更高版本,您可能需要查看Janning的答案.(*AnnotationMethodHandlerAdapter*现已弃用.) (2认同)