Friday, 23 November 2018

Spring web mvc: @ModelAttribute: Map the request parameters to java object

By using @ModelAttribute annotation, you can bind the request parameters to a java object.

@RequestMapping(value = "getEmpDetails", method = RequestMethod.POST)
public ModelAndView getWelcomeMessage(@ModelAttribute Employee emp) {
         emp.setId(getRandomNumber());
         String msg = "Details of the employee";

         ModelAndView modelAndView = new ModelAndView("employeeDetails");
         modelAndView.addObject("message", msg);
         modelAndView.addObject("employeeDetails", emp);
         return modelAndView;
}

As you notify above example, I am assigning all the request parameters to the model object emp.

Find the below working application.

HelloWorldController.java
package com.sample.myApp.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.sample.myApp.model.Employee;

@Controller
public class HelloWorldController {

 @RequestMapping(value = "getEmpDetails", method = RequestMethod.POST)
 public ModelAndView getWelcomeMessage(@ModelAttribute Employee emp) {

  emp.setId(getRandomNumber());
  String msg = "Details of the employee";

  ModelAndView modelAndView = new ModelAndView("employeeDetails");
  modelAndView.addObject("message", msg);
  modelAndView.addObject("employeeDetails", emp);
  return modelAndView;
 }

 private static int getRandomNumber() {
  return new java.util.Random().nextInt();
 }

} 


Address.java
package com.sample.myApp.model;

public class Address {

 private String city;
 private String country;
 private String street;
 private String houseNumber;

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getHouseNumber() {
  return houseNumber;
 }

 public void setHouseNumber(String houseNumber) {
  this.houseNumber = houseNumber;
 }

} 


Employee.java
package com.sample.myApp.model;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private Address address;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

} 

Create employeeDetails.jsp file under WEB-INF/jsp folder.

employeeDetails.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>

 <table>
  <thead>${message}</thead>

  <tr>
   <td>First Name</td>
   <td>${employeeDetails.firstName}</td>
  </tr>

  <tr>
   <td>Last Name</td>
   <td>${employeeDetails.lastName}</td>
  </tr>

  <tr>
   <td>Address</td>
   <td>${employeeDetails.address.city},${employeeDetails.address.country},
    ${employeeDetails.address.street},
    ${employeeDetails.address.houseNumber}</td>
  </tr>
 </table>
</body>
</html>


Create web.xml, HelloWorld-servlet.xml files under WEB-INF folder.

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:component-scan
  base-package="com.sample.myApp" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

Create index.jsp file under webapp folder.

index.jsp
<html>
<head>
<title>User Information Page</title>
</head>
<div id="login_form">
 <form method="post" action="/springdemo/getEmpDetails" id="f1">
  <table>
   <tr>
    <td>firstName :</td>
    <td><input type="text" name="firstName" value="" /></td>
   </tr>

   <tr>
    <td>lastName :</td>
    <td><input type="text" name="lastName" value="" /></td>
   </tr>

   <tr>
    <td>city :</td>
    <td><input type="text" name="address.city" value="" /></td>
   </tr>


   <tr>
    <td>country :</td>
    <td><input type="text" name="address.country" value="" /></td>
   </tr>


   <tr>
    <td>street :</td>
    <td><input type="text" name="address.street" value="" /></td>
   </tr>


   <tr>
    <td>house number :</td>
    <td><input type="text" name="address.houseNumber" value="" /></td>
   </tr>

   <tr>
    <td><input type="submit" name="submit" value="submit"
     style="font-size: 18px;" /></td>
   </tr>
  </table>
 </form>
</div>
</html>


Total project structure looks like below.


Run the application on server. It opens below form.



Fill some information and click on Submit button. You can able to see below output.


@RequestMapping(value = "getEmpDetails", method = RequestMethod.POST)
public ModelAndView getWelcomeMessage(@ModelAttribute Employee emp) {
         modelAndView.addObject("employeeDetails", emp);
         return modelAndView;
}

You can also rewrite the above snippet like below.

@RequestMapping(value = "getEmpDetails", method = RequestMethod.POST)
public ModelAndView getWelcomeMessage(@ModelAttribute("employeeDetails") Employee emp) {
         return modelAndView;

}



Previous                                                 Next                                                 Home

No comments:

Post a Comment