Java 如何将IP地址绑定到Spring 3@ModelAttribute?
我的方法是这样的:Java 如何将IP地址绑定到Spring 3@ModelAttribute?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我的方法是这样的: @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);
@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";
}
因此,我需要通过调用HttpServletRequest
上的getRemoteAddr()
将IP地址绑定到Foo
对象。我曾尝试为Foo
创建CustomEditor
,但这似乎不是正确的方法@InitBinder
看起来更有希望,但我还没有找到方法
IP地址在对象上是必需的,Spring与JSR-303Bean验证相结合将给出一个验证错误,除非它存在
解决这个问题最优雅的方法是什么?您可以使用
@modeldattribute
-注释的方法用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());
}
非常感谢,我从未在Spring文档中看到过这样的示例。我选择第一种方式是因为纯粹的
@InitBinder
方式在施法上有些笨拙。