spring mvc 可以修剪从表单中获取的所有字符串吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2691667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:03:03  来源:igfitidea点击:

Can spring mvc trim all strings obtained from forms?

springspring-mvc

提问by Gordian Yuan

I know struts2 default config will trim all strings obtained from forms.

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

For example:

例如:

I type

我打字

"   whatever "
以表格形式提交,我会得到
"whatever"
字符串已被自动修剪

Does spring mvc have this function too? THX.

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

回答by Janning

Using Spring 3.2 or greater:

使用 Spring 3.2 或更高版本:

@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:

使用 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;
    }
}

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]

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

回答by Lonre Wang

register this property editor: org.springframework.beans.propertyeditors.StringTrimmerEditor

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

Example for AnnotionHandlerAdapter:

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>

回答by Patrick

You can also use Spring's conversion service, which has the added benefit of working with <mvc:annotation-driven/>and with Spring Webflow. As with the other answers, the major downside is that this is a global change and can't be disabled for certain forms.

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

You'll need a converter to do the trimming

您需要一个转换器来进行修剪

public class StringTrimmingConverter implements Converter<String, String> {

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

}

Then define a conversion service that knows about your converter.

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

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

and tie that in to mvc.

并将其绑定到 mvc。

<mvc:annotation-driven conversion-service="applicationConversionService"/>

If you use Spring Webflow then it require a wrapper

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

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

and a setting on your flow builder

以及您的流程构建器上的设置

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

回答by Sarvar Nishonboev

Just customized the above code in order to adjust to Spring Boot, if you want to explicit trim function for some fields in the form, you can show them as below:

上面的代码只是为了适应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));
        }
}

回答by Arthur Ronald

You can user a Spring-MVC Interceptor

您可以使用 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;
    }

And set up your HandlerMapping interceptors property

并设置您的 HandlerMapping 拦截器属性

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

Or use a Servlet Filter

或者使用 Servlet 过滤器

回答by Jaille Chen

first,trim requestparam which is String,you can create a class and implimplements WebBingdingInitializer

首先,修剪 requestparam 是 String,你可以创建一个类并实现 WebBingdingInitializer

 @ControllerAdvice
public class CustomWebBindingInitializer implements WebBindingInitializer {

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

please use componentScan make this Class to be a Spring Bean.

请使用 componentScan 使这个类成为 Spring Bean。

But, I don't know how to trim the String value in requestBody JSON data.

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