Monday, November 4, 2024

Spring MVC @RequestParam Annotation Example

In this Spring MVC @RequestParam annotation example we’ll see how request data which is passed as query parameter in the URI can be extracted using @RequestParam 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 to get value of those request parameters.

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=UTF-8"
    pageEncoding="UTF-8"%>
<!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 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

Sunday, November 3, 2024

Java Stream - min() With Examples

In Java Stream API there is a min() method that is used to get the minimum element of this stream according to the provided Comparator. In this post we’ll see some examples of the min() method.

Syntax of the Stream.min() method

min is a terminal operation and its syntax is as given below-

Optional<T> min(Comparator<? super T> comparator)

Here comparator argument is an implementation of the Comparator to compare elements of this stream.

Method returns an Optional describing the minimum element of this stream, or an empty Optional if the stream is empty.

Stream.min is considered a special case of a reduction operation as it takes a sequence of input elements and combines them into a single summary result.

min() method Java examples

1. Finding min value from a stream of numbers.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamMin {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 9, 14, 1, 59, 23, 77, 10, 12, 4);
      Optional<Integer> minElement = numList.stream().min(Integer::compare);
      if(minElement.isPresent()){
        System.out.println("Minimum element: " + minElement.get());
      }
  }
}

Output

Minimum element: 1

2. In the following example custom comparator is passed as an argument to the min() method to get minimum method as per the passed Comparator.

public class StreamMin {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 9, 14, 1, 59, 23, 77, 10, 12, 4);
      Optional<Integer> minElement = numList.stream().min(new MyComparator());
      if(minElement.isPresent()){
        System.out.println("Minimum element: " + minElement.get());
      }
  }
}

class MyComparator implements Comparator<Integer>{
  @Override
  public int compare(Integer o1, Integer o2) {
    return o1.compareTo(o2);
  }
}

Output

Minimum element: 1

3. Using Stream.min() method with custom object. In the example, objects of Employee class are used and the objective is to find minimum salary using the min() method of the Java Stream API.

Employee class used is as given here.

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
}

In the example mapToInt() method is used to get the salary part of the employee object which is then passed to the min() to get the minimum salary.

public class StreamMin {
  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 24, "Mark", 'M', 9000), 
                new Employee("E004", 37, "Rani", 'F', 10000),
                new Employee("E005", 32, "Anuj", 'M', 12000));  
     OptionalInt minEmpSal = empList.stream()
                .mapToInt(Employee::getSalary)
                .min();
      if(minEmpSal.isPresent()){
        System.out.println("Minimum salary: " + minEmpSal.getAsInt());
      }
  }
}

Output

Minimum salary: 5000

That's all for this topic Java Stream - min() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - max() With Examples
  2. Java Stream - filter() With Examples
  3. Java Stream - distinct() With Examples
  4. Java Stream - findFirst() With Examples
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. How to Sort ArrayList of Custom Objects in Java
  2. equals() And hashCode() Methods in Java
  3. Type Casting in Java With Conversion Examples
  4. StringJoiner Class in Java With Examples
  5. Writing a File Asynchronously Java Program
  6. Spring Integration With Quartz Scheduler
  7. Operator Overloading in Python
  8. Angular Access Control CanActivate Route Guard Example