Spring MVC 4 - @RequestParam annotation example

Posted on April 6, 2017


Technologies used:   JDK 1.8.0_121 | Spring 4.3.7.RELEASE | Maven 3.3.9 | Apache Tomcat 7.0.47 | Eclipse Neon.3

The @RequestParam annotation binds a web request parameter (i.e. query string) to a method parameter in a controller.

The following code snippet shows the usage of @RequestParam annotation.

Request URL with query string -

http://localhost:8080/request1?name=David

Accessing value of name parameter in handler method -

@RequestMapping("/request1")
public String handler(@RequestParam(name = "name") String name) {
	
}

Let’s see a complete example of how to use the @RequestParam annotation to bind request parameters to method parameters in a controller.

Jar dependencies

Add the following jar dependencies in your pom.xml file.

  <!-- Spring MVC Dependency -->
  <dependency>
	 <groupId>org.springframework</groupId>
	 <artifactId>spring-webmvc</artifactId>
	 <version>4.3.7.RELEASE</version>
  </dependency>

  <!-- JSTL Dependency -->
  <dependency>
	 <groupId>javax.servlet.jsp.jstl</groupId>
	 <artifactId>javax.servlet.jsp.jstl-api</artifactId>
	 <version>1.2.1</version>
  </dependency>
  <dependency>
	 <groupId>taglibs</groupId>
	 <artifactId>standard</artifactId>
	 <version>1.1.2</version>
  </dependency>

  <!-- Servlet Dependency -->
  <dependency>
	 <groupId>javax.servlet</groupId>
	 <artifactId>javax.servlet-api</artifactId>
	 <version>3.1.0</version>
	 <scope>provided</scope>
  </dependency>

  <!-- JSP Dependency -->
  <dependency>
	 <groupId>javax.servlet.jsp</groupId>
	 <artifactId>javax.servlet.jsp-api</artifactId>
	 <version>2.3.1</version>
	 <scope>provided</scope>
  </dependency>

Controller class

Create a @Controller class whose handler methods are annotated with @RequestMapping annotation and method parameters are annotated with @RequestParam annotation.

Use the @ResponseBody annotation to bind the handler method’s return type to the web response body.

MyController.java

package com.boraji.tutorial.spring.controller;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author imssbora
 */
@Controller
public class MyController {

  /*
    * Binding a request parameter to a method parameter using 'name' or 'value'
    * attribute of @RequestParam
    */
   @RequestMapping("/request1")
   @ResponseBody
   public String handler(@RequestParam(name = "name") String name) {

      return "URL parameter <br> " 
            + "name =" + name;
   }

  /*
    * Binding request parameters to method parameters without using 'name' or
    * 'value' attribute of @RequestParam.
    */
   @RequestMapping("/request2")
   @ResponseBody
   public String handler(@RequestParam String firstName, @RequestParam String lastName) {

      return "URL parameters - <br>" 
            + " firstName = " + firstName + " <br>" 
            + " lastName = " + lastName;
   }

  /*
    * If method parameter type is not String then Spring automatically converts
    * to the appropriate type such as int, long, float etc.
    */
   @RequestMapping("/request3")
   @ResponseBody
   public String handler(@RequestParam("name") String name, 
         @RequestParam("age") int age,
         @RequestParam("amount") double amount, 
         @RequestParam("active") boolean active) {

      return "URL parameters - <br>" 
            + " name = " + name + " <br>" 
            + " age = " + age + " <br>" 
            + " amount = " + amount
            + " <br>" + " active = " + active;
   }

  /*
    * Binding all request parameters to Map
    */
   @RequestMapping("/request4")
   @ResponseBody
   public String handler(@RequestParam Map<String, String> params) {

      StringBuilder builder = new StringBuilder();
      builder.append("URL parameters - <br>");
      for (Entry<String, String> entry : params.entrySet()) {
         builder.append(entry.getKey() + " = " + entry.getValue() + "<br>");
      }
      return builder.toString();
   }

  /*
    * The required=false attribute of @RequestParam annotation is used to make
    * method parameter as Optional i.e. it bind a null value to method parameter
    * if request parameter is not present.
    */
   @RequestMapping("/request5")
   @ResponseBody
   public String handler(@RequestParam("firstName") String firstName,
         @RequestParam(name = "middleName", required = false) String middleName,
         @RequestParam("lastName") String lastName) {

      return "URL parameters - <br>" 
            + " firstName = " + firstName + " <br>" 
            + " middleName = " + middleName + " <br>"
            + " lastName = " + lastName;
   }

  /*
    * Binding date and time request parameters to LocalDate and LocalTime
    * using @DateTimeFormat and @RequestParam
    */
   @RequestMapping("/request6")
   @ResponseBody
   public String handler(
         @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam("date") LocalDate date,
         @DateTimeFormat(pattern = "HH:mm:ss") @RequestParam("time") LocalTime time) {

      return "URL parameters - <br>" 
            + " date = " + date + " <br>" 
            + " time = " + time;
   }

  /*
    * Binding request parameter to array and list
    */
   @RequestMapping("/request7")
   @ResponseBody
   public String handler(@RequestParam("country") String[] country, 
         @RequestParam("city") List<String> city) {

      return "URL parameters - <br>" 
            + " country = " + Arrays.asList(country) + " <br>" 
            + " city = " + city;
   }

  /*
    * Using default value of a method parameter if request parameter is not
    * provided or has an empty value
    */
   @RequestMapping("/request8")
   @ResponseBody
   public String handler(@RequestParam(name = "code", defaultValue = "10") int code
        ) {

      return "URL parameters - <br>" 
            + " code = " + code;
   }

}

 

Spring configuration

Create a web @Configuration class annotated with @EnableWebMvc and @ComponentScan as follows.

WebConfig.java

package com.boraji.tutorial.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * @author imssbora
 */

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {

   @Bean
   public InternalResourceViewResolver resolver() {
      InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      resolver.setViewClass(JstlView.class);
      resolver.setPrefix("/WEB-INF/views/");
      resolver.setSuffix(".jsp");
      return resolver;
   }

}

The @EnableWebMvc enables default Spring MVC configuration and provides the functionality equivalent to <mvc:annotation-driven/> element in XML based configuration.

The @ComponentScan scans the stereotype annotations (@Controller@Service etc...) in a package specified by basePackages attribute.

 

Servlet container initialization

Create a container initializer class by extending the AbstractAnnotationConfigDispatcherServletInitializer class as follows.

MyWebAppInitializer.java

package com.boraji.tutorial.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @author imssbora
 */
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return new Class[] {};
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}

The AbstractAnnotationConfigDispatcherServletInitializer class, implements the WebApplicationInitializer, is implemented in Servlet 3.0+ environments in order to configure the ServletContext programmatically.

 

Build + Deploy + Run application

Use the following maven commands to build, deploy and run embedded Tomcat server.

mvn clean install  (This command triggers war packaging)

mvn tomcat7:run (This command run embedded tomcat and deploy war file automatically)

You can refer this link to learn how to run the above commands in Eclipse IDE.

 

Type the following URLs in browser's address bar and see output…

1 - http://localhost:8080/request1?name=David%20Miller

SpringMVC-RequestParam1.png

2 - http://localhost:8080/request2?firstName=David&lastName=Miller

SpringMVC-RequestParam2.png

3 - http://localhost:8080/request3?name=David&age=32&amount=1200.50&active=1

SpringMVC-RequestParam3.png

4 - http://localhost:8080/request4?name=David&age=32&country=India&city=Jaipur

SpringMVC-RequestParam4.png

5 - http://localhost:8080/request5?firstName=David&lastName=Miller

SpringMVC-RequestParam5.png

6 - http://localhost:8080/request6?date=2017-12-12&time=12:54:52

SpringMVC-RequestParam6.png

7 - http://localhost:8080/request7?country=USA&country=India&country=Japan&city=Jaipur&city=Delhi&city=Jakarta

SpringMVC-RequestParam7.png

8 - http://localhost:8080/request8

SpringMVC-RequestParam8.png

Download Sources