Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 689
WeGa Avatar asked Sep 09 '15 09:09

WeGa


People also ask

Can a request param be null?

Method parameters annotated with @RequestParam are required by default. will correctly invoke the method. When the parameter isn't specified, the method parameter is bound to null.

What is the difference between PathVariable and RequestParam?

2) @RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable is more suitable for RESTful web services where URL contains values.

What does the @RequestParam annotation do?

In Spring MVC, the @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method. So, it ignores the requirement of HttpServletRequest object to read the provided data.

What is the difference between @RequestParam and @RequestBody?

@RequestParam makes Spring to map request parameters from the GET/POST request to your method argument. @RequestBody makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods.


1 Answers

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)
like image 179
Sergio Avatar answered Oct 12 '22 09:10

Sergio