Signup/Sign In

Spring @RequestParam Annotation

Spring @RequestParam annotation is used to fetch the value of a parameter in the form request. In Spring MVC, "request parameters" map to query parameters, form data.

For example, if we want to get parameter(user_name) value from a requested URL then we can use @RequestParam annotation. We just need to provide a parameter name.

http://localhost:8080/spring-mvc-app/showdata?user_name=studytonight

In the above URL, the parameter is: user_name and value: studytonight and we can fetch it in our application like:

@RequestMapping("showdata")
public String userForm(@RequestParam("user_name") String name, Model model)
{
	model.addAttribute("name", name);
	return "user-data";		
}

The @RequestParam annotation uses several attributes like name, required, defaultvalue, etc. We can use them in our application based on the use cases.

DefaultValue Attribute

Set DefaultValue for the parameter, to avoid null value. We can use this attribute to handle missing values. If the parameter does not contain any value then this default value will be supplied.

@RequestMapping("showdata")
public String userForm(@RequestParam(defaultValue = "No_value") String name, Model model)
{
	model.addAttribute("name", name);
	return "user-data";		
}

Required Attribute

The required attribute is used to handle exceptions in case of missing data. It throws HTTP Status 400 – Bad Request (Required String parameter 'user_name' is not present). To avoid this exception, we can use the required attribute.

@RequestMapping("showdata")
public String userForm(@RequestParam(required = false) String name, Model model)
{
	model.addAttribute("name", name);
	return "user-data";		
}

Java 8 Optional Class

We can use Optional class to avoid exceptions in case of missing data by providing a value. It is similar to the default attribute but can be used if you are working with java 8 or higher version.

@RequestMapping("showdata")
public String userForm(@RequestParam Optional<String> name, Model model)
{
    String name1 = name.orElseGet(()->"no value found"); 
	model.addAttribute("name", name1);
	return "user-data";		
}

@RequestParam Attributes

The following are the attributes list of @RequestParam annotation.

Type and Element

Description

String defaultValue

This element is used to set a default value to the parameter.

String name

It indicates the name of the request parameter to bind to.

boolean required

It is used to set whether the parameter is required.

String value

It is similar to name elements and can be used as an alias.

Spring @RequestParam Annotation Working Example

Let's understand by example and create a maven-based Spring application and add these files. After that run this example using a web server (Apache Tomcat). See the source code of the project.

// HelloController.java

It is a controller class file that uses @Controller annotation. It shows a user form and by submitting that form it shows the data entered by the user.

package com.studytonight.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {
	
	@RequestMapping("/")
	public String showForm() {
		return "user-form";
	}
	
	@RequestMapping("showdata")
	public String userForm(@RequestParam("user_name") String name, Model model)
	{
			model.addAttribute("name", name);
			return "user-data";		
	}
}

// user-form.jsp

It is a JSP page that shows an HTML form to get user information.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Form</title>
</head>
<body>
<form action="showdata" method="Get">
	<label>Enter User Name: </label><input type="text" name="user_name"><br/><br/>
	<input type="submit" />
</form>
</body>
</html>

// user-data.jsp

This JSP page shows the data submitted by the user.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello JSP</title>
</head>
<body>
<strong>Hello,</strong>
${name}
</body>
</html>

// spring-mvc-app-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">

	<!-- Step 3: Add support for component scanning -->
	<context:component-scan base-package="com.studytonight.controller" />

	<!-- Step 4: Add support for conversion, formatting and validation support -->
	<mvc:annotation-driven/>

	<!-- Step 5: Define Spring MVC view resolver -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

// web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">

	<display-name>spring-mvc-app</display-name>

	<absolute-ordering />

	<!-- Spring MVC Configs -->

	<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc-app-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
</web-app>

// pom.xml

This file contains all the dependencies of this project such as spring jars, servlet jars, etc. Put these dependencies into your project to run the application.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.studytonight</groupId>
	<artifactId>spring-mvc-app</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.3.0</version>
		</dependency>
	</dependencies>
	<properties>
		<spring.version>5.2.8.RELEASE</spring.version>
	</properties>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Run the Application

After successfully completing the project and adding the dependencies run the application and you will get the output as below.

This is the second JSP page that shows the user name submitted by the above user name.



About the author:
I am a Java developer by profession and Java content creator by passion. I have over 5 years of experience in Java development and content writing. I like writing about Java, related frameworks, Spring, Springboot, etc.