Spring MVC Tutorial

Spring MVC Annotation @PathVariable Example

@PathVariable:

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

Example

package com.candidjava.springmvc.controller;
 
import java.util.Map;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class CountryController
{
 
  @RequestMapping("/welcomeMap/{countryName}/{userName}")
  public ModelAndView helloMap(@PathVariable Map<String, String> pathVars)
  {
 
    String country = pathVars.get("countryName");
    String name = pathVars.get("userName");
    
 
    ModelAndView model = new ModelAndView("page");
    model.addObject("msg", "Country : " + country + " <=======>  Name :  " + name);
 
    return model;
  }
 
  @RequestMapping("/welcomeString/{countryName}/{userName}")
  public ModelAndView helloString(@PathVariable("countryName") String cn, @PathVariable("userName") String un)
  {
    ModelAndView model = new ModelAndView("page");
    model.addObject("msg", "Country : " + cn + " <=======>  Name :  " + un);
    return model;
 
  }
}

Screenshot

 

Download

@PathVariable annotation spring example war

@PathVariable annotation spring example zip