Tuesday, May 17, 2016

Spring MVC Tutorial part III - How to use pathVariable annotation

@PathVariable Annotation

We can make dynamic URIs with the help of PathVariable annotation. You can map this pathVariable argument with Map object. Let us check below code. 

@Controller

 public class orderController {

 @RequestMapping("/orderDetails/{orderName}")
        public String showOrder(Model model, @PathVariable("orderName") String orderName) {

             model.addAttribute("orderName", orderName);

             return "showOrder"; // view name
     }
 }

From the above , the URI will from like below. Just assume you are running locally,

For Laptop order, URI like below,
http://localhost:8080/orderDetails/LaptopOrder

For Desktop order, URI like below,
http://localhost:8080/orderDetails/DesktopOrder

Some people may get confuse about request param and pathVariable. Both are different. Above URI is the example for pathVariable.
Below is the example for request param . 
http://localhost:8080/orderDetails?orderName=LaptopOrder

@PathVariable with Map

@RequestMapping(value="/{orderName}/{userName}",method=RequestMethod.GET)
public String getOrderUserName(@PathVariable Map<String, String> pathVars, Model model) {

    String name = pathVars.get("userName");
    String order = pathVars.get("orderName");

    model.addAttribute("msg", "Test" + name + " Spring MVC " + order);
    return "home";// ViewName
}

From the above, we have used Map<String, String> to map pathVariables for orderName and userName. After that, whenever data need , you can retrieve from pathVars map object.

Note: 

<mvc:annotation-driven /> needs to be added into your dispatcher-servlet.xml file. It will give an explicit support for mvc controllers annotation. Means, @RequestMapping, @Controller etc.,

<context:annotation-config> - It will support @Autowired, @Required , @PostConstruct etc.,

No comments:

Post a Comment