我的方法是这样的:
@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 地址绑定(bind)到 Foo
对象,这可能是通过在 HttpServletRequest
上调用 getRemoteAddr()
来实现的。我试过为 Foo
创建 CustomEditor
,但这似乎不是正确的方法。 @InitBinder
看起来更有前途,但我还没有找到方法。
对象的 IP 地址是强制性的,Spring 结合 JSR-303 bean 验证将给出验证错误,除非它存在。
解决这个问题最优雅的方法是什么?
最佳答案
您可以使用 @ModelAttribute
注释的方法用 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());
}
关于java - 如何将 IP 地址绑定(bind)到 Spring 3 @ModelAttribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328257/