Spring 3 MVC请求验证 [英] Spring 3 MVC request validation
问题描述
我有一个Spring 3.2应用程序,我创建了一个使用基于令牌的安全性的REST API。每个REST JSON有效内容都包含一个令牌字段,用于执行安全验证。
I have a Spring 3.2 application and I've created a REST API that uses a token-based security. Every REST JSON payload contains a "token" field that is used to perform security validation.
控制器方法如下:
@RequestMapping(value = "/something", method = RequestMethod.POST)
public
@ResponseBody
Map something(@RequestBody SomethingParams params) {
}
其中SomethingParams有一个标记
字段,并由Spring从JSON自动填写请求的主体。
where SomethingParams has a token
field, and is automatically filled in by Spring from the JSON body of the request.
有没有办法在所有控制器方法上自动调用验证器来检查诸如SomethingParams之类的参数是否具有有效的令牌?
Is there a way to automatically have a validator invoked on all the controller methods to check that parameters such as SomethingParams have a valid token?
以前我使用过拦截器,并且令牌包含在查询字符串中,但是现在,因为它在请求的主体中,我将不得不在拦截器中解析JSON为了检查它。由于Spring已经解析了JSON以绑定参数,我很好奇是否有更聪明的方法。理想情况下只需要一些全局或控制器级设置(不是每种方法)。
Previously I used an Interceptor, and the token was included in the query string, but now, since it's in the body of the request, I would have to parse the JSON in the interceptor in order to check it. Since Spring already parses the JSON to bind the parameters, I'm curious if there's a smarter way. Ideally just with some global or controller-level settings (not per method).
推荐答案
你可以使用spring Validator
用于此类情况。
You can use a spring Validator
for such cases.
@Component
public class SomethingParamsValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(SomethingParams.class);
}
@Override
public void validate(Object o, Errors errors) {
SomethingParams sp = (SomethingParams)o;
validateToken(sp.getToken(), errors);
}
private void validateToken(String token, Errors errors) {
if (!TokenUtils.isValid(token)) {
errors.rejectValue("token", "foo", "Token is invalid");
}
}
}
然后你在你的注册控制器
添加以下方法
Then you register it in your Controller
by adding the following method
@Autowired
SomethingParamsValidator somethingParamsValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(somethingParamsValidator);
}
最后你需要添加的是 @Valid SomethingParams
对象上的注释,它将被验证。
Finally all you have to add is the @Valid
annotation on your SomethingParams
object and it will be validated.
@RequestMapping(value = "/something", method = RequestMethod.POST)
public @ResponseBody Map something(@Valid @RequestBody SomethingParams params) {
// ...
}
这篇关于Spring 3 MVC请求验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!