我在Spring MVC项目中有表单对象的Spring Validator,我需要做一些部分基于客户端IP地址的验证。是否有可能在验证器中获得类似request.getRemoteAddr()的内容?
//controler
public String saveForm(@Valid @ModelAttribute("command") MyCommand myCommand, BindingResult result) {
//some code
return "viewName";
}
//Validator
public class MyValidator implements Validator {
@Override
public void validate(Object target, Errors errors) {
String requestIp = ?
}
}
答案 0 :(得分:1)
我想到的第一种方法是使用RequestContextHolder
来获取用户的请求:
((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr()
您还需要将以下行添加到web.xml
:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>