Saturday, 24 November 2018

Spring web mvc: @ModelAttribute on method

This is continuation to my previous post. IN my previous post, we mapped the request parameters to a model object and pass the model object to the view using @ModelAttribute annotation like below.

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

You can even apply @ModelAttribute annotation on top of a method to remove the boilerplate code.

Example
@Controller
public class HelloWorldController {

         @RequestMapping("/hello")
         public ModelAndView getHelloMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");

                  modelAndView.addObject("greeting", "Good morning");
                  modelAndView.addObject("quote", "Live not one’s life as though one had a thousand years, but live each day as the last.");

                  return modelAndView;
         }

         @RequestMapping("/welcome")
         public ModelAndView getWelcomeMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");

                  modelAndView.addObject("greeting", "Good morning");
                  modelAndView.addObject("quote", "There are two great days in a person's life - the day we are born and the day we discover why.");

                  return modelAndView;
         }
}

As you see above controller class, below statement is duplicated in getHelloMessage(), getWelcomeMessage() methods.
modelAndView.addObject("greeting", "Good morning");

How can I remove this boilerplate code?
Move the common code to some other function and annotate it with @ModelAttribute annotation.

@ModelAttribute
public void commonData(Model model) {
         model.addAttribute("greeting", "Good morning");
}

Find the below working example.

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

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

@Controller
public class HelloWorldController {

 @ModelAttribute
 public void commonData(Model model) {
  model.addAttribute("greeting", "Good morning");
 }

 @RequestMapping("/hello")
 public ModelAndView getHelloMessage() {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("quote",
    "Live not one’s life as though one had a thousand years, but live each day as the last.");

  return modelAndView;
 }

 @RequestMapping("/welcome")
 public ModelAndView getWelcomeMessage() {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("quote",
    "There are two great days in a person's life - the day we are born and the day we discover why.");

  return modelAndView;
 }
}


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

hello.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>

 <h1>${message}</h1>
 <h2>${quote}</h2>
</body>
</html>
Create web.xml, HelloWorld-servlet.xml file 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>

<body>
 <h1>Hello World</h1>
</body>
</html>

Project structure looks like below.

Run the application server and hit below URL.






Previous                                                 Next                                                 Home

No comments:

Post a Comment