下面是我的方法:
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String create(@ModelAttribute("foo") @Valid final Foo foo,
final BindingResult result, final Model model) {
if (result.hasErrors())
return form(model);
fooService.store(foo);
return "redirect:/foo";
}
因此,我需要将IP地址绑定到Foo
对象,方法可能是在HttpServletRequest
上调用getRemoteAddr()
。我尝试过为Foo
创建CustomEditor
,但这似乎不是正确的方式。@InitBinder
看起来更有前途,但我还没有弄清楚是怎么回事。
对象上的IP地址是强制的,Spring结合JSR-303bean验证将会给出一个验证错误,除非它存在。
解决这个问题最好的方法是什么?
发布于 2010-02-25 02:25:40
您可以使用@ModelAttribute
-annotated方法使用IP地址预填充对象:
@ModelAttribute("foo")
public Foo getFoo(HttpServletRequest request) {
Foo foo = new Foo();
foo.setIp(request.getRemoteAddr());
return foo;
}
@InitBinder("foo")
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("ip"); // Don't allow user to override the value
}
编辑:只使用@InitBinder
就可以做到这一点:
@InitBinder("foo")
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
binder.setDisallowedFields("ip"); // Don't allow user to override the value
((Foo) binder.getTarget()).setIp(request.getRemoteAddr());
}
https://stackoverflow.com/questions/2328257
复制相似问题