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

时间:2010-04-22 14:25:22

标签: spring spring-mvc

我知道struts2 default config会修剪从表单中获取的所有字符串。

例如:

我在表单中输入

"   whatever "
并提交,我会得到
"whatever"
该字符串已自动修剪

spring mvc也有这个功能吗? THX。

6 个答案:

答案 0 :(得分:38)

使用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所说 - 它也适用于密码,因为在服务器端输入[type = password]和输入[type = text]

之间没有区别

答案 1 :(得分: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>

答案 2 :(得分:4)

您还可以使用Spring的转换服务,它具有使用<mvc:annotation-driven/>和Spring Webflow的额外好处。与其他答案一样,主要的缺点是这是一个全球性的变化,对某些形式不能被禁用。

您需要转换器才能进行修剪

public class StringTrimmingConverter implements Converter<String, String> {

    @Override
    public String convert(String source) {
       return source.trim();
    }

}

然后定义了解转换器的转换服务。

<bean id="applicationConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
    <list>
        <bean class="mypackage.util.StringTrimmingConverter"/>
    </list>
    </property>
</bean>

并将其与mvc。

联系起来
<mvc:annotation-driven conversion-service="applicationConversionService"/>

如果您使用Spring Webflow,那么它需要一个包装器

 <bean id="defaultConversionService" class="org.springframework.binding.convert.service.DefaultConversionService">
    <constructor-arg ref="applicationConversionService"/>
</bean>

和流程构建器上的设置

<flow:flow-builder-services id="flowBuilderServices" conversion-service="defaultConversionService" development="true"  validator="validator" />

答案 3 :(得分:2)

您可以使用Spring-MVC拦截器

public class TrimInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Enumeration<String> e = request.getParameterNames();
        while(e.hasMoreElements()) {
            String parameterName = e.nextElement();

            request.setParameter(parameterName, request.getParameter(parameterName).trim());
        }

        return true;
    }

设置你的HandlerMapping拦截器属性

<bean id="interceptorTrim" class="br.com.view.interceptor.TrimInterceptor"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" p:interceptors-ref="interceptorTrim"/>
}

或使用Servlet过滤器

答案 4 :(得分:1)

只需自定义上面的代码即可适应Spring Boot,如果您想为表单中的某些字段显式修剪函数,则可以如下所示:

@Component
@ControllerAdvice
public class ControllerSetup {
    @InitBinder({"dto", "newUser"})
        public void initBinder(WebDataBinder binder) {
          binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
          binder.registerCustomEditor(String.class, "userDto.username", new StringTrimmerEditor(false));
          binder.registerCustomEditor(String.class, "userDto.password", new DefaultStringEditor(false));
          binder.registerCustomEditor(String.class, "passwordConfirm", new DefaultStringEditor(false));
        }
}

答案 5 :(得分:0)

首先,修剪requestString为String,您可以创建一个类并实现WebBingdingInitializer

 @ControllerAdvice
public class CustomWebBindingInitializer implements WebBindingInitializer {

    @InitBinder
    @Override
    public void initBinder(WebDataBinder webDataBinder, WebRequest webRequest) {
        webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
}

请使用componentScan使此类成为Spring Bean。

但是,我不知道如何在requestBody JSON数据中修剪String值。