[spring-mvc] Spring mvc @PathVariable

Can you give me a brief explanation and a sample in using @PathVariable in spring mvc? Please include on how you type the url?
I'm struggling in getting the right url to show the jsp page. Thanks.

This question is related to spring-mvc

The answer is


If you have url with path variables, example www.myexampl.com/item/12/update where 12 is the id and create is the variable you want to use for specifying your execution for instance in using a single form to do an update and create, you do this in your controller.

   @PostMapping(value = "/item/{id}/{method}")
    public String getForm(@PathVariable("id") String itemId ,  
        @PathVariable("method") String methodCall , Model model){

     if(methodCall.equals("create")){
            //logic
      }
     if(methodCall.equals("update")){
            //logic
      }

      return "path to your form";
    }

have a look at the below code snippet.

@RequestMapping(value = "edit.htm", method = RequestMethod.GET) 
    public ModelAndView edit(@RequestParam("id") String id) throws Exception {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("user", userinfoDao.findById(id));
        return new ModelAndView("edit", modelMap);      
    }

If you want the complete project to see how it works then download it from below link:-

UserInfo Project on GitLab


Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.

@RequestMapping(value = "/download/{documentId}", method = RequestMethod.GET)
public ModelAndView download(@PathVariable int documentId) {
    ModelAndView mav = new ModelAndView();
    Document document =  documentService.fileDownload(documentId);

    mav.addObject("downloadDocument", document);
    mav.setViewName("download");

    return mav;
}

@PathVariable used to fetch the value from URL

for example: To get some question

www.stackoverflow.com/questions/19803731

Here some question id is passed as a parameter in URL

Now to fetch this value in controller all you have to do is just to pass @PathVariable in the method parameter

@RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
    public String getQuestion(@PathVariable String questionId){
    //return question details
}

Have a look at the below code snippet.

@RequestMapping(value="/Add/{type}")
public ModelAndView addForm(@PathVariable String type ){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("addContent");
    modelAndView.addObject("typelist",contentPropertyDAO.getType() );
    modelAndView.addObject("property",contentPropertyDAO.get(type,0) );
    return modelAndView;
}

Hope it helps in constructing your code.


Let us assume you hit a url as www.example.com/test/111 . Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using @PathVariable as follows :

@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}

SO the variable value is retrieved from the url


It is one of the annotation used to map/handle dynamic URIs. You can even specify a regular expression for URI dynamic parameter to accept only specific type of input.

For example, if the URL to retrieve a book using a unique number would be:

URL:http://localhost:8080/book/9783827319333

The number denoted at the last of the URL can be fetched using @PathVariable as shown:

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)

public String showBookDetails(@PathVariable("ISBN") String id,

Model model){

model.addAttribute("ISBN", id);

return "bookDetails";

}

In short it is just another was to extract data from HTTP requests in Spring.