Path Variables In Spring Framework

Spring Framework offers to handle URI method parameters by using @PathVariable annotation

@Controller
@RequestMapping("admin")
public class PathVarController {

@RequestMapping("/welcome/{springPathVariable}/{page}")
public ModelAndView pathVariableTest(@PathVariable("page") String name, @PathVariable("springPathVariable") String pathVariable ) {

ModelAndView mav = new ModelAndView("pathVariable");
mav.addObject("message", " "+ name+" Your PathVariable is : "+pathVariable);
return mav;
}
}


@PathVariable without variable name.
In this case path variable name must be same as URI parameter variable name.

@Controller
@RequestMapping("admin")
public class PathVarController {
@RequestMapping("/welcome/{pathVariable}")
public ModelAndView pathVariableTest(@PathVariable String pathVariable ) {
ModelAndView mav = new ModelAndView("pathVariable");
mav.addObject("message", " Your PathVariable is : "+pathVariable);
return mav;
}
}

Using Map with @PathVariable for multiple variables
If the method parameter is Map<String, String> or MultiValueMap<String, String> is populated with all path variable names and values.

@Controller
public class PathVariableController { 
    @RequestMapping("/welcome/{springPathVariable}/{userName}")
    public ModelAndView pathVariableTest(@PathVariable Map<String,String> pathVars) {
        String name = pathVars.get("userName");
        String pathVariable = pathVars.get("springPathVariable");
      
        ModelAndView mav = new ModelAndView("pathVariable");
        mav.addObject("message", " "+ name+" Your PathVariable is : "+pathVariable);
        return mav;
    }
}

// In case when you used multiple pathVariable, then how much path variable inter in parameter!
// AT that case spring provide,  for that
// in xml file we mention <mvc:annoation-driven>  i.e.

<mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="com.techa2zsolution.web.controller"></context:component-scan>
   
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix" ><value>/WEB-INF/pages/</value> </property>
        <property name="suffix"><value>.jsp</value> </property>
    </bean>
    
 Spring provide to handle regular expression during the request handler method
at that time request mapping annotation consist parameter colon regular expression, when they return true process the requested method, expression is like.

@RequestMapping("{name: [a-zA-Z]+}")  
public String handleRequest(@PathVariable("name") String userName, Model model )  {
     model.addAttribute("msg",  "User Name is :  "+userName);
     return "my-page";
}