java - 如何将 IP 地址绑定(bind)到 Spring 3 @ModelAttribute?

标签 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);
    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/

相关文章:

java - (Maven项目)无法找到或加载主类 "class"

java - 上下文初始化失败 org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'homeController'

java - 学习 Spring 的 @RequestBody 和 @RequestParam

java - jdbc Postgres 驱动程序中的 `ssl` 和 `useSSL` 有什么区别?

java - 使用 DecimalFormat 格式化美元值

java - 如何使用 java Runtime 执行交互式 shell 脚本?

java - 自定义 PropertyPlaceholderConfigurer 无法解析嵌入的属性值

java - Spring MVC : Get Unnamed Request Parameter

spring-boot - 使用Spring Data JPA规范获取投影接口(interface)

java - 无法在intellij中将Spring mvc部署到tomcat