【问题标题】:How to bind IP address to a Spring 3 @ModelAttribute?如何将 IP 地址绑定到 Spring 3 @ModelAttribute?
【发布时间】:2010-02-24 17:58:29
【问题描述】:

我的方法如下所示:

@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-303 bean 验证将给出验证错误,除非它存在。

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

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,我在 Spring 文档中从未见过这样的示例。我选择了第一种方式,因为纯粹的@InitBinder 方式在选角上显得有些笨拙。
    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2012-04-16
    • 1970-01-01
    • 2011-06-19
    • 2019-04-13
    相关资源
    最近更新 更多