11

I am sending following request that need to be handled by Spring-MVC but it does not.

http://localhost:2001/MyProject/flights/find?origin=LAX&destination=WA&departure=&arrival=&return=false

Code

@Controller
@RequestMapping("/flights")
public class FlightController {

   @RequestMapping(value = "/find?origin={origin}&destination={destination}&departure={departure}&arrival={arrival}&return={return}", method = RequestMethod.GET)
    public String findFlight(@PathVariable String origin,
            String destination, Date departure, Date arrival, boolean return) {

2 Answers 2

26

That is not the correct way (or place) to use @PathVariable. You need to use @RequestParam.

@Controller
@RequestMapping("/flights")
public class FlightController {
  @RequestMapping("/find")
  public String findFlight(@RequestParam String origin
                          , @RequestParam String destination
                          , @RequestParam(required = false) Date departure
                          , @RequestParam(required = false) Date arrival
                          , @RequestParam(defaultValue = "false", required = false, value = "return") Boolean ret) { ... }
}

Note that return is a keyword in Java so you cannot use it as a method parameter name.

You will also have to add a java.beans.PropertyEditor for reading the dates because the dates will (presumably) be in a specific format.

7
  • I see thanks, then when can I use @PathVariable? when they are in /param/param2/param4 format?
    – Jack
    Commented Mar 22, 2015 at 5:05
  • Correct, @PathVariable is for when you want to extract information from the request path. The request path ends at ? after which request parameters start.
    – manish
    Commented Mar 22, 2015 at 5:07
  • I even changed the Date to String but does not work.
    – Jack
    Commented Mar 22, 2015 at 5:11
  • What do you mean by "does not work"? Is there an error, are the parameters null? This is the correct mechanism. See documentation.
    – manish
    Commented Mar 22, 2015 at 5:11
  • the parameters are not null, it does not call findFlight method.
    – Jack
    Commented Mar 22, 2015 at 5:16
1

Try this, may be it works:

 @RequestMapping("/find")
  public String findFlight(@RequestParam("origin") String origin
                          , @RequestParam("destination") String destination,....
2
  • thanks the correct answer is already accepted. Do you think the answer is wrong?
    – Jack
    Commented Mar 23, 2015 at 6:13
  • @Jack it gives you another option in case you don't want to name the url parameters the same as the methods parameters. Commented Nov 8, 2019 at 14:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.