代码之家  ›  专栏  ›  技术社区  ›  hleinone

如何将IP地址绑定到Spring3@ModelAttribute?

  •  3
  • hleinone  · 技术社区  · 16 年前

    我的方法是这样的:

    @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 可能通过调用 getRemoteAddr() 在…上 HttpServletRequest . 我试过创造 CustomEditor 对于 福 @InitBinder

    IP地址在对象上是强制的,Spring结合JSR-303bean验证将给出一个验证错误,除非它在那里。

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

    1 回复  |  直到 16 年前
        1
  •  7
  •   axtavt    16 年前

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