java - Spring 3 MVC request validation -


i have spring 3.2 application , i've created rest api uses token-based security. every rest json payload contains "token" field used perform security validation.

the controller methods this:

@requestmapping(value = "/something", method = requestmethod.post) public @responsebody map something(@requestbody somethingparams params) { } 

where somethingparams has token field, , automatically filled in spring json body of request.

is there way automatically have validator invoked on controller methods check parameters such somethingparams have valid token?

previously used interceptor, , token included in query string, now, since it's in body of request, have parse json in interceptor in order check it. since spring parses json bind parameters, i'm curious if there's smarter way. ideally global or controller-level settings (not per method).

you can use spring validator 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 invalid");     }   } } 

then register in controller adding following method

@autowired somethingparamsvalidator somethingparamsvalidator;  @initbinder protected void initbinder(webdatabinder binder) {     binder.setvalidator(somethingparamsvalidator); } 

finally have add @valid annotation on somethingparams object , validated.

@requestmapping(value = "/something", method = requestmethod.post) public @responsebody map something(@valid @requestbody somethingparams params) {     // ... } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -