Dmitrii Bundin Dmitrii Bundin - 7 days ago 7
Java Question

Bean Validation and requested parameter in spring mvc

Is it possible to use validators for validation request parameters from

javax.validation.constraints
package in any way? I.e. like the following:

@Controller
public class test {

@RequestMapping("/test.htm")
public String test(@RequestParam("name") @NotNull String name)
{
return "index";
}
}

Answer

Use this way:

public class Comment{

    @NotEmpty
    @Length(max = 140)
    private String text;

    //Methods are omitted.
}

Now use @Valid in controller

 @Controller
    public class CommentController {

        @RequestMapping(value = "/api/comment", method = RequestMethod.POST)
        @ResponseBody
        public Comment add(@Valid @RequestBody Comment comment) {
            return comment;
        }
    }

When you are applying @Valid for Comment object in your cotroller,it will apply the validation mentioned in Comment class and its attribute like

@NotEmpty
    @Length(max = 140)
    private String text;

You can also check this out for little alternate way of doing: http://techblogs4u.blogspot.in/2012/09/method-parameter-validation-in-spring-3.html

Comments