Spring @PathVariable Annotation Example
In spring, the @PathVariable
annotation is used to bind the URI template variables to the handler method parameters of a controller in the Spring MVC framework. In this tutorial, we will show how to implement the Spring @PathVariable Annotation with the Spring MVC framework.
1. Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring Mvc Framework
Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
1.3 Spring @PathVariable Annotation
The @PathVariable
annotation in spring binds the URI template variables to the handler method parameters of a controller. A URI template can contain one or more path variables enclosed by the curly braces ({ }
) in the following format:
http://www.example.com/user/{name}/{age}
The @PathVariable
annotation in spring mvc consists of the following optional attributes i.e.:
name
: It is the String type attribute and is the name of the query string parameter. This is what the code snippet looks like:@RequestMapping(value="/str/{countryName}", method=RequestMethod.GET) public ModelAndView getData(@PathVariable(name="countryName") String cname) { …. }
required
: It is a Boolean type attribute and is used when the parameter value is required. If the required parameter is missing in the URI template then the application will return an HTTP status 400 error page (i.e. a bad request). The default value of this attribute istrue
but it can be overridden tofalse
. This is what the code snippet looks like:@RequestMapping(value="/str/{countryName}", method=RequestMethod.GET) public ModelAndView getData(@PathVariable(name="countryName", required=true) String cname) { …. }
value
: It is a String type attribute and is an alias for the name attribute. This is what the code snippet looks like:@RequestMapping(value="/str/{countryName}", method=RequestMethod.GET) public ModelAndView getData(@PathVariable(value="countryName") String cname) { …. }
1.3.1 Using multiple @PathVariable annotations
Sometimes a handler method can have any number of the @PathVariable
annotation. To solve this, developers will have to make a handler method having the same number of the URI template variables i.e.
@RequestMapping(value="/str/{countryName}/{userName}", method=RequestMethod.GET) public ModelAndView getData(@PathVariable("countryName") String cname, @PathVariable("userName") String uname) { …. }
This can be a tedious job if the query string has any number of template variables. Thus, to save the developers from this tedious work, spring provided the support for binding the URI template variables to a Map
. Hence, all the URI template string names and values are populated to a Map
and this is what the modified code snippet looks like:
@RequestMapping(value="/str/{countryName}/{userName}", method=RequestMethod.GET) public ModelAndView getData(@PathVariable Map<String, String> path) { …. }
Now, open up the Eclipse IDE and let’s see how to use the @PathVariable
annotation in the spring framework!
2. Spring @PathVariable Annotation Example
Here is a step-by-step guide for implementing this annotation in the spring mvc framework.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mvc.spring</groupId> <artifactId>SpringMvcPathVariable</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Servlet API, Spring Mvc etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the spring mvc framework. The rest dependencies such as Spring Beans, Spring Core etc. will be automatically resolved by Maven. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.mvc</groupId> <artifactId>SpringMvcPathVariable</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMvcPathVariable Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- Servlet API Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- Spring Framework Dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.7.RELEASE</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Configuration Files
Let’s write all the configuration files involved in this application.
3.2.1 Web Deployment Descriptor
The web.xml
file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>SpringMvcPathVariable</display-name> <servlet> <servlet-name>mvcpathvariabledispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mvcpathvariabledispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.2.2 Spring Configuration File
To configure the spring framework, developers need to implement a bean configuration file i.e. mvcpathvariabledispatcher-servlet.xml
which provide an interface between the basic Java class and the outside world. Add the following code to it:
mvcpathvariabledispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.spring.mvc" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Do note:
- This file is loaded by the spring’s Dispatcher Servlet which receives all the requests coming into the application and dispatches them to the controller for processing
- This file has the
InternalResourceViewResolver
bean declaration that tells the framework how to find the physicalJSP
files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name
3.3 Java Class Creation
Let’s create a simple controller class where the @Controller
annotation specifies this class as a spring controller and is responsible for handling the incoming request which is configured by the @RequestMapping
annotation. The handler methods of the controller class are mapped to two URI template variables. Add the following code to it:
Ctrl.java
package com.spring.mvc; 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.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class Ctrl { // Method with multiple arguments appended in the url. @RequestMapping(value="/str/{countryName}/{userName}", method=RequestMethod.GET) public ModelAndView getStringData(@PathVariable("countryName") String cname, @PathVariable("userName") String uname) { ModelAndView m = new ModelAndView(); m.addObject("msg", "Country: " + cname + " <=======> Name: " + uname); m.setViewName("success"); return m; } // Method with multiple arguments and fetching it from the map. @RequestMapping(value="/map/{countryName}/{userName}", method=RequestMethod.GET) public ModelAndView getMapData(@PathVariable Map<String, String> path) { String country = path.get("countryName"), name = path.get("userName"); ModelAndView m = new ModelAndView(); m.addObject("msg", "Country: " + country + " <=======> Name: " + name); m.setViewName("success"); return m; } }
3.4 JSP View
Spring Mvc supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple result view in SpringMvcPathVariable/src/main/webapp/WEB-INF/views
.
3.4.1 Index Page
This is the welcome page of this example having two links to demonstrate the usage of @PathVariable
annotation in spring mvc framework. Add the following code to it:
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page isELIgnored="false"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Index</title> </head> <body> <center><h3>@PathVariable annotation in Spring MVC</h3></center> <hr /> <div id="links"> <a id="str" href="/SpringMvcPathVariable/str/India/Daniel">PathVariable using String</a> <div> </div> <a id="map" href="/SpringMvcPathVariable/map/Europe/Charlotte">PathVariable using Map</a> </div> </body> </html>
3.4.2 Success Page
This is the success page of this tutorial and it displays the output. Add the following code to it:
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page isELIgnored="false"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Success</title> </head> <body> <center><h3>@PathVariable annotation in Spring MVC</h3></center> <hr /> <div>Message: <span>${msg}</span></div> <div> </div> <a id="back" href="../../index.jsp">Go back</a> </body> </html>
4. Run the Application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project Demo
Open your favorite browser and hit the following URL to display the output page.
http://localhost:8082/SpringMvcPathVariable/index.jsp
Server name (localhost) and port (8082) may vary as per your tomcat configuration.
Users can click on the links to understand the working of the @PathVariable
annotation in spring framework. That’s all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and don’t forget to share!
6. Conclusion
In this section, developers learned how the @PathVariable
annotation can be used to fetch the URI template variables. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of @PathVariable
annotation in Spring Mvc.
You can download the full source code of this example here: SpringMvcPathVariable