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]之间没有区别
小智 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)
| 归档时间: |
|
| 查看次数: |
19217 次 |
| 最近记录: |