Accepting Request Param and Path Variable in Spring Controller

Most modern web applications allow end users to interact with it by sending data back to the server. Depending on the data send by the end user the server responds differently to the them.

Spring MVC provides various ways that a client browser can send data back to the server. These include:

  • Request Parameters
  • Path Variables
  • Form inputs

In this article we will see how to write controllers that can handle request parameters and path variables.

Accepting Request/ Query Parameters

Spring provides the @RequestParam annotation to accept request parameters in Controller's handler methods.

Consider the following request url's:

http://www.cubearticle.com/users/profiles?user=Ashutosh
http://www.cubearticle.com/users/profiles?user=Robert

To accept the request parameters in the url's shown above, we can use the below code in controller's handler method:

@RequestMapping("/users/profiles")
public String showProfilePageReqParam(@RequestParam("user") String username, Model model){
    model.addAttribute("username", username);
    return "userProfile";
}

If the parameter name in the request and the variable name in the handler method's @RequestParam annotated parameter are identical we can simple use @RequestParam, the value attribute can be derived automatically. See below:

http://www.cubearticle.com/users/profiles?username=Ashutosh

@RequestMapping("/users/profiles") public String showProfilePageReqParam(@RequestParam String username, Model model){ model.addAttribute("username", username); return "userProfile"; }

Accepting Path Variables

To accept path variables in Controller's handler method we can make use of @PathVariable annotation.

Consider the following request url's:

http://www.cubearticle.com/users/profiles/Ashutosh
http://www.cubearticle.com/users/profiles/John

To accept the above path variables, we can use the below code in controller's handler method:

@RequestMapping(value="/users/profiles/{username}", method= RequestMethod.GET)
public String showProfilePathVar(@PathVariable("username") String user, Model model){
    model.addAttribute("username", user);
    return "userProfile";
}

Similar to @RequestParameter annotation, we can omit the value attribute in @PathVariable annotation, if the path variable's placeholder in the @RequestMapping annotation is identical to the variable name in the handler method's @PathVariable annotated parameter. See below:

@RequestMapping(value="/users/profiles/{username}", method= RequestMethod.GET)
public String showProfilePathVar(@PathVariable String username, Model model){
    model.addAttribute("username", username);
    return "userProfile";
}

Sample Application

Let's create a simple application to demonstrate request parameters and path variables. We have used Java config for Spring configuration; however, we are skipping the configuration part here. To know about configuration you can refer to this article.

We will start by creating the home page of our application. It just has some anchor tags, some of them using request parameters and others using path variables as shown below:

<div>
<h3>View Profile: Request Parameters</h3>
<ol>
    <li><a href="profiles?username=Ashutosh">Ashutosh</a></li>
    <li><a href="profiles?username=Robin">Robin</a></li>
    <li><a href="profiles?username=Rose">Rose</a></li>
</ol>
<br />
<h3>View Profile: Path Variables</h3>
<ol>
    <li><a href="profiles/Adam">Adam</a></li>
    <li><a href="profiles/Deepak">Deepak</a></li>
    <li><a href="profiles/John">John</a></li>
</ol>
</div>

Now we need to write our Spring controller that will be used to capture these request parameter or path variables in the handler methods. Shown below is the controller of our sample application:

@Controller
@RequestMapping("/profiles")
public class MyController {
	
    @RequestMapping
    public String showProfilePageReqParam(@RequestParam String username, Model model){
	model.addAttribute("username", username);
	return "userProfile";
    }
	
    @RequestMapping(value="/{username}", method= RequestMethod.GET)
    public String showProfilePathVar(@PathVariable("username") String user, Model model){
	model.addAttribute("username", user);
	return "userProfile";
    }	
}

Notice the class level @RequestMapping annotation, it would apply to all the @RequestMapping annotated methods of the class.

So, showProfilePageReqParam() method will handle "/profile", since it has an empty value attribute in the @RequestMapping annotation.

Similarly, showProfilePathVar() method will handle "/profile/<pathVar>", "/profile" from class level @RequestMapping and "/<pathVar>" form its own @RequestMapping annotation.

In the handler method we are adding the username to the model object so that we can be able to retrieve this information in the view.

Finally, we need a jsp page that would be used to display the user's profile page. Shown below is our userProfile jsp where we retrieve the username which was set in the model object by the controller.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Profile</title>
</head>
<body>
	<c:out value="${username}" />'s Profile Page
</body>
</html>

Download Source Code

You can download the source code of the Sample Application discussed in this article.

POPULAR ARTICLES

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article