Master java skills

Spring MVC

MVC stands for Model-View-Controller. This module of Spring framework is used to build web applications. Model represents data, View represents view files (html, jsp), whereas Controller represents java classes that have logic to process the incoming requests.

The core of Spring MVC is DispatcherServlet class. It works as the front controller in the web application, meaning all the incoming requests are first intercepted by DispatcherServlet. Then it maps the request to the appropriate Controller. Let’s understand the flow of Spring MVC using the below diagram.

Spring MVC flow

  1. As the request comes for the web application, it is intercepted by DispatcherServlet.
  2. By analyzing the url, the DispatcherServlet with the help of HandlerMapping finds out the appropriate controller that can serve the request, and forwards the request to it.
  3. After processing the request, the controller generates a ModelAndView object that contains the data and the view information.
  4. With the help of ViewResolver and ModelAndView object, DispatcherServlet gets the information of the right view file (html, jsp etc)
  5. View is generated with data and given back as the response to the browser.

Spring MVC Example

  1. Create a maven project using the archetype ‘spring-mvc-archetype‘ with groupId ‘co.ntier‘. If you want to learn how to create a maven project using archetype, click here. Project structure should look like below

pom.xml

2. Since we have created the project using archetype, the pom.xml will have all the required dependencies. If you have created the project without archetype, then add the following dependencies.

	<properties>
		<java.version>1.6</java.version>
		<spring.version>3.1.0.RELEASE</spring.version>
		<cglib.version>2.2.2</cglib.version>
	</properties>

	<dependencies>
		<!-- Spring core & mvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>

		<!-- CGLib for @Configuration -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>${cglib.version}</version>
			<scope>runtime</scope>
		</dependency>


		<!-- Servlet Spec -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.4</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

web.xml

3. Update web.xml to add DispatcherServlet entry. Since we have created the project using maven archetype, this entry would already be there

Just make sure package name is correct for contextConfigLocation. For this example, it is com.javatrainingschool

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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>mvc-spring-example</display-name>
	<context-param>
		<param-name>contextClass</param-name>
		<param-value>
			org.springframework.web.context.support.AnnotationConfigWebApplicationContext
		</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>SpringDispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextClass</param-name>
			<param-value>
				org.springframework.web.context.support.AnnotationConfigWebApplicationContext
			</param-value>
		</init-param>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>com.javatrainingschool</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringDispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
</web-app>

Spring MVC bean configuration class in package com.javatrainingschool.config

Create a java class named MvcConfiguration.java. Make sure to keep correct name for basePackages attribute of @ComponentScan. For this example, it is com.javatrainingschool

package com.javatrainingschool.config;

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

@Configuration
@ComponentScan(basePackages="com.javatrainingschool")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{

	@Bean
	public ViewResolver getViewResolver(){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
	}
}

Create model class Drink in package com.javatrainingschool.model

package com.javatrainingschool.model;

public class Drink {

	private int id;
	private String name;
	private String type;

	//getter and setter method
	//constructors
	//toString
		
}

Create DrinkController class in package com.javatrainingschool.controller

package com.javatrainingschool.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.javatrainingschool.model.Drink;
import com.javatrainingschool.service.DrinkService;

//http://localhost:8080/drink/
@Controller
@RequestMapping("/drink")
public class DrinkController {

	@Autowired
	private DrinkService service;

	@RequestMapping("/display")
	public ModelAndView displayDrinkInfo() {
		
		ModelAndView mv = new ModelAndView("displayDrink");
		
		List<Drink> drinks = service.displayDrink();
		
		mv.addObject("drinks", drinks);
		
		return mv;
	}
	
	@RequestMapping("/addDrink")
	public ModelAndView addDrink() {
		
		ModelAndView mv = new ModelAndView("addDrink");
		Drink drink = new Drink();
		
		mv.addObject("command", drink);
		
		return mv;
	}
	
	@RequestMapping(value = "/saveDrink", method = RequestMethod.POST)
	public ModelAndView save(@ModelAttribute("drink") Drink drink) {
		
		ModelAndView mv = new ModelAndView("displayDrink");
		service.addDrink(drink);
		List<Drink> drinks = service.displayDrink();
		mv.addObject("drinks", drinks);
		mv.addObject("msg", drink.getName() + " added successfully");
		return mv;
	}
}

Create DrinkService class in package com.javatrainingschool.service

package com.javatrainingschool.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.javatrainingschool.model.Drink;

@Service
public class DrinkService {
	
	
	private static List<Drink> drinks = new ArrayList<Drink>();
	
	static {
		Drink d1 = new Drink(1, "Virgin Pina Colada", "Cold Beverage");
		Drink d2 = new Drink(2, "Cappi Nirvana", "Cold Beverage");
		Drink d3 = new Drink(3, "Ginger Tea", "Hot Beverage");
		Drink d4 = new Drink(4, "Cafe Latte", "Hot Beverage");
		drinks.add(d1);
		drinks.add(d2);
		drinks.add(d3);
		drinks.add(d4);
	}
	
	
	public List<Drink> displayDrink(){
		return drinks;
	}
	
	
	public List<Drink> addDrink(Drink drink){
		drinks.add(drink);
		return drinks;
	}
}

Create addDrink.jsp file under WEB-INF/views folder

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<body>
	<h1>Add Drink</h1>
	<form:form method="post" action="saveDrink">
		<table>
			<tr>
				<td>Drink Id :</td>
				<td><form:input path="id" /></td>
			</tr>
			<tr>
				<td>Drink Name :</td>
				<td><form:input path="name" /></td>
			</tr>
			<tr>
				<td>Drink Type :</td>
				<td><form:input path="type" /></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="Save Drink" /></td>
			</tr>
		</table>
	</form:form>
</body>
</html>

Create displayDrink.jsp file under WEB-INF/views folder

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<body>

	<h1>Drinks Menu</h1><br>
	<div> ${msg}  </div><br>
	<table border="2" width="70%" cellpadding="2">
		<tr>
			<th>Id</th>
			<th>Drink Name</th>
			<th>Drink Type</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
		<c:forEach var="drink" items="${drinks}">
			<tr>
				<td>${drink.id}</td>
				<td>${drink.name}</td>
				<td>${drink.type}</td>
				<td><a href="editemp/${drink.id}">Edit</a></td>
				<td><a href="deleteemp/${drink.id}">Delete</a></td>
			</tr>
		</c:forEach>
	</table>
	<br />
	<a href="addDrink">Add a Drink</a>
</body>
</html>

Add jstl dependency in pom.xml file

Add below dependency in your pom.xml file

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
</dependency>

Project structure

project structure should look like this

Deploy and test the application on Tomcat

If Tomcat is not already installed on your machine, click below to download and configure it into STS.

How to download and configure Tomcat

After successful installation of the server, deploy your application onto it. After deployment is done on the server, run it and test your application.

Hit below url

http://localhost:8080/my-spring-mvc-project/drink/display

http://localhost:8080/my-spring-mvc-project/drink/addDrink