How to check request parameter is not empty String in @RequestMapping params?

WeGa picture WeGa · Sep 9, 2015 · Viewed 33.9k times · Source

In my controller I have String parameter, containing some id, that should not be null of empty string. I'm wondering, is there any way to check it is not empty String in @RequestMapping params? I have tried to solve it in some ways

@RequestMapping(value = someURL, params = {"id"})
public SomeResponse doSomething(@RequestParam(required = true) String id)

@RequestMapping(value = someURL, params = {"!id="})
public SomeResponse doSomething(@RequestParam(required = true) String id)

@RequestMapping(value = someURL, params = {"!id=\"\""})
public SomeResponse doSomething(@RequestParam(required = true) String id)

with no success. As I understand, both params = {"id"} and @RequestParam(required = true) can only check that parameter id is presented in request (!= null).

It is most likely that I have to check that with code in controller boby, like

if (id == null || id.isEmpty()) {
    return someErrorResponse;
}

but please correct me if I wrong. Thanks in advance.

P.S. my app is running on Java 1.7 SE in Apache Tomcat 7.0.62 container

Answer

Sergio picture Sergio · Sep 20, 2016

According to the Spring code that consumes that annotation

org.springframework.web.servlet.mvc.annotation.ServletAnnotationMappingUtils.checkParameters(String[], HttpServletRequest)

Something like this should work:

@RequestMapping(value = someURL, params = {"id!="})
public SomeResponse doSomething(@RequestParam(required = true) String id)