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 有一个token
字段,并且由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");
}
}
}
然后通过添加以下方法将其注册到 Controller
中
Then you register it in your Controller
by adding the following method
@Autowired
SomethingParamsValidator somethingParamsValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(somethingParamsValidator);
}
最后,您需要添加的是 SomethingParams
对象上的 @Valid
注释,它将被验证.
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屋!