Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring REST-ful uri with optional querystring

Tags:

java

rest

spring

The normal uri which triggers the default controller to get all cars is just "/cars"

I want to be able to search for cars aswell with an uri, for example: "/cars?model=xyz" which would return a list of matching cars. All the request parameters should be optional.

The problem is that even with the querystring the default controller triggers anyway and I always get "all cars: ..."

Is there a way to do this with Spring without a separate search uri (like "/cars/search?..")?

code:

@Controller
@RequestMapping("/cars")
public class CarController {
@Autowired
private CarDao carDao;

@RequestMapping(method = RequestMethod.GET, value = "?")
public final @ResponseBody String find(
        @RequestParam(value = "reg", required = false) String reg,
        @RequestParam(value = "model", required = false) String model
        )
{
    Car searchForCar = new Car();
    searchForCar.setModel(model);
    searchForCar.setReg(reg);
    return "found: " + carDao.findCar(searchForCar).toString();
}

@RequestMapping(method = RequestMethod.GET)
public final @ResponseBody String getAll() {
    return "all cars: " + carDao.getAllCars().toString();
} 
}
like image 979
user2170710 Avatar asked Dec 16 '22 13:12

user2170710


2 Answers

You can use

@RequestMapping(method = RequestMethod.GET, params = {/* string array of params required */})
public final @ResponseBody String find(@RequestParam(value = "reg") String reg, @RequestParam(value = "model") String model)
    // logic
}

ie, the @RequestMapping annotation has a property called params. If all of the parameters that you specify are contained in your request (and all other RequestMapping requirements match), then that method will be called.

like image 165
Sotirios Delimanolis Avatar answered Jan 04 '23 09:01

Sotirios Delimanolis


Try a variation of this:

    @Controller
    @RequestMapping("/cars")
    public clas CarController
    {
        @RequestMapping(method = RequestMethod.get)
        public final @ResponseBody String carsHandler(
            final WebRequest webRequest)
        {
            String parameter = webRequest.getParameter("blammy");

            if (parameter == null)
            {
                return getAll();
            }
            else
            {
                return findCar(webRequest);
            }
        }
    }
like image 29
DwB Avatar answered Jan 04 '23 08:01

DwB