how can i add validation to a spring boot rest endpoint with a string parameter?

Viewed 987

how to validate a spring boot rest endpoint with a String parameter, here is the sample of my endpoint.

@ResponseBody
@RequestMapping(value = "/getProfile", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getProfile(@RequestBody @Valid @NotEmpty String profileId){}

even thought i added @valid and @NonEmpty constraint its not getting validated.

but its working for a other classes. for eg,

@ResponseBody
    @RequestMapping(value = "/saveProfiles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> saveProfiles(@RequestBody @Valid PersistProfilesRequest request){}

here all the fields in PersistProfilesRequest class which have a constrain applied is validating properly.

validation is not happening for method parameter with java class like String and Map.

i am using spring boot 1.3.0 with hibernate validator.

how can i add validation to a rest endpoint with a string parameter?

EDIT

i am using junit and mockmvc to test the endpoint, below is the test case

@Test
public void testGetProfile() throws Exception{

    String profileId = "   ";

    this.mockMvc.perform(post("/getProfile").content(profileId).accept(MediaType.APPLICATION_JSON).contentType("application/json"))
                .andDo(print())
                .andExpect(status().isInternalServerError());

}
1 Answers

You can try to annotate your controller class with @Validated. In my case it helped.

@Validated
@RestController
@RequestMapping(path = "/api/somethin")
public class LegacyRestController {
Related