2010-02-24 73 views
3

这里是我的方法是如何的样子:如何将IP地址绑定到Spring 3 @ModelAttribute?

@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"; 
} 

所以,我需要大概通过调用HttpServletRequestgetRemoteAddr()到IP地址Foo对象绑定。我已经尝试为Foo创建CustomEditor,但它似乎不是正确的方法。 @InitBinder看起来更有希望,但我还没有找到如何。

该对象上的IP地址是强制性的,Spring与JSR-303 bean验证组合会产生验证错误,除非它存在。

什么是最优雅的方式来解决这个问题?

回答

7

您可以使用@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()); 
} 
+1

非常感谢,我从来没有在Spring文档中看到过这样的例子。我选择了第一种方式,因为纯粹的'@ InitBinder'方式在铸造方面看起来有些笨拙。 – hleinone 2010-02-24 22:34:45

相关问题