Tuesday, May 12, 2020

Spring MVC @RequestParam Annotation Example

In this Spring MVC @RequestParam annotation example we’ll see how request data can be passed to the controller using @RequestParam annotation along with @RequestMapping annotation.

Spring @RequestParam and @RequestMapping annotation

If you are passing request parameters as query parameters, then you can use @RequestParam along with @RequestMapping annotation in the Spring controller method.

For example- /spring-mvc/getUser?userId=101

Here userId is the query parameter that can be retrieved using the @RequestParam annotation.

Spring web MVC example with @RequestParam annotation

In this Spring MVC example we’ll have a JSP (home page) with 3 fields, entered values in these 3 fields are sent as query parameters with in the URL.

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - Home JSP</title>
</head>
<body>
  <div>Message- ${message}</div>
  <form name="userform" action="showUser" method="get">
    <table>
      <tr>
        <td>
          First Name: <input type="text" id="firstName" name="firstName">
        </td>
      </tr>
      <tr>
        <td>
          Last Name: <input type="text" id="lastName" name="lastName">
        </td>
      </tr>
      <tr>
        <td>
          DOB: <input type="text" id="dob" name="dob">
        </td>
      </tr>        
    </table>               
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Spring MVC - Controller class

In the controller class there are two methods. First method showHome() is annotated with RequestMapping value parameter as “/” and returns the logical view name as “home” which results in the display of home.jsp.

Another method showUser() serves to the request where path is “/showUser”. In this method the method parameters are annotated with @RequestParam. The value parameter with in the @RequestParam should match the query parameter name. For example this handler method will serve the requests in the form - /showUser?firstName=Leonard&lastName=Nimoy&dob=1956-05-23

The value of the query parameter will be assigned to the corresponding method parameter.

MessageController.java

import java.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MessageController {
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String showHome(Model model) {
  model.addAttribute("message", "MVC Example with dynamic URL");
  return "home";
 }
 
 @RequestMapping(value = "/showUser", method = RequestMethod.GET)
 public String showUser(@RequestParam("firstName") String firstName, 
                @RequestParam("lastName") String lastName, 
                @DateTimeFormat(pattern = "yyyy-MM-dd")
                @RequestParam("dob") LocalDate dob,
                Model model) { 

  model.addAttribute("firstName", firstName);
  model.addAttribute("lastName", lastName);
  model.addAttribute("dob", dob);
  return "user";
 }
}

The parameters of the method showUser() which have the values of the query parameters assigned to them are added to the Model. The method returns the logical view name as “user” which is resolved to the view user.jsp.

Note that if method parameter name is same as the query parameter name in the @RequestMapping then the value parameter with @RequestParam is optional. So the same method can also be written as-

@RequestMapping(value = "/showUser", method = RequestMethod.GET)
public String showUser(@RequestParam String firstName, 
             @RequestParam String lastName, 
             @DateTimeFormat(pattern = "yyyy-MM-dd")
             @RequestParam LocalDate dob,
             Model model) {

 ...
 ...
}

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - User</title>
</head>
<body>
<div>First Name: ${firstName}</div>
<div>Last Name: ${lastName}</div>
<div>DOB: ${dob}</div>
</body>
</html>

Home page

Spring MVC with @RequestParam

User page

Spring MVC with RequestParam annotation

Default value for RequestParam parameters in Spring MVC

If you want to provide default value for the RequestParam parameters if the query parmeters are not there in the request then you can use defaultValue attribute of the @RequestParam. The default value is used as a fallback when the request parameter is not provided or has an empty value.

@RequestMapping(value = "/showUser", method = RequestMethod.GET)
public String showUser(
  @RequestParam(value="firstName", defaultValue="Test") String firstName, 
  @RequestParam(value="lastName", defaultValue="User") String lastName, 
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  @RequestParam(value="dob", defaultValue="2000-01-01") LocalDate dob,
  Model model) { 
 ...
 ...
}

required attribute in Spring @RequestParam annotation

You can set whether the parameter is required or not using required attribute. Default value for the required attribute is true, which means an exception is thrown if the parameter is missing in the request. By setting required as false null value is assigned if the parameter is not present in the request.

For example if you want to make DOB as optional.

@RequestMapping(value = "/showUser", method = RequestMethod.GET)
public String showUser(
  @RequestParam(value="firstName", defaultValue="Test") String firstName, 
  @RequestParam(value="lastName", defaultValue="User") String lastName, 
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  @RequestParam(value="dob", required=false) LocalDate dob,
  Model model) {
 ...
 ...
}

That's all for this topic Spring MVC @RequestParam Annotation Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Web MVC Tutorial
  2. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  3. Spring MVC File Download Example
  4. Spring MVC Redirect Example
  5. Spring Transaction Management JDBC Example Using @Transactional Annotation

You may also like-

  1. Internationalization (i18n) Using MessageSource in Spring
  2. @Resource Annotation in Spring Autowiring
  3. Spring Bean Life Cycle
  4. Bean Definition Inheritance in Spring
  5. Difference Between ArrayList And CopyOnWriteArrayList in Java
  6. Java ReentrantLock With Examples
  7. this Keyword in Java With Examples
  8. Checking Number Prime or Not Java Program

No comments:

Post a Comment