Spring MVC
Spring MVC
A Spring MVC is a Java framework which is used to build web applications. It follows the
Model-View-Controller design pattern. It implements all the basic features of a core spring
framework like Inversion of Control, Dependency Injection.
A Spring MVC provides an elegant solution to use MVC in spring framework by the help
of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models, and views.
o Model - A model contains the data of the application. A data can be a single
object or a collection of objects.
o Controller - A controller contains the business logic of an application. Here, the
@Controller annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format.
Generally, JSP+JSTL is used to create a view page. Although spring also supports
other view technologies such as Apache Velocity, Thymeleaf and FreeMarker.
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as the
front controller. It is responsible to manage the flow of the Spring MVC
application.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
The @Requestmapping annotation is used to map the class with the specified URL
name.
HelloController.java
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/")
public String display()
{
return "index";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
</beans>
index.jsp
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
index.jsp
<html>
<body>
<a href="hello">Click here...</a>
</body>
</html>
HelloController.java
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String redirect()
{
return "viewpage";
}
@RequestMapping("/helloagain")
public String display()
{
return "final";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The prefix+string returned by controller+suffix page will be invoked for the view
component.
This xml file should be located inside the WEB-INF directory.
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<html>
<body>
<a href="helloagain">SpringMVC</a>
</body>
</html>
final.jsp
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
index.jsp
<html>
<body>
<a href="hello1">Spring MVC</a> ||
<a href="hello2">Spring Boot</a>
</body>
</html>
HelloController1.java
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController1 {
@RequestMapping("/hello1")
public String display()
{
return "viewpage1";
}
}
HelloController2.java
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController2 {
@RequestMapping("/hello2")
public String display()
{
return "viewpage2";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
Viewpage2.jsp
<html>
<body>
<p>Welcome to Spring Boot Tutorial</p>
</body>
</html>
index.jsp
<html>
<body>
<form action="hello">
UserName : <input type="text" name="name"/> <br><br>
Password : <input type="text" name="pass"/> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
o The HttpServletRequest is used to read the HTML form data provided by the user.
o The Model contains the request data and provides it to view page.
HelloController.java
package com.java;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String display(HttpServletRequest req,Model m)
{
//read the provided form data
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
viewpage.jsp
<html>
<body>
${message}
</body>
</html>
errorpage.jsp
<html>
<body>
${message}
<br><br>
<jsp:include page="/index.jsp"></jsp:include>
</body>
</html>
Including form data, it also maps the request parameter to query parameter and parts in
multipart requests. If the method parameter type is Map and a request parameter name
is specified, then the request parameter value is converted to a Map else the map
parameter is populated with all request parameter names and values.
index.jsp
<html>
<body>
<form action="hello">
UserName : <input type="text" name="name"/> <br><br>
Password : <input type="text" name="pass"/> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
o The @RequestParam is used to read the HTML form data provided by a user and bind it
to the request parameter.
o The Model contains the request data and provides it to view page.
HelloController.java
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
@RequestMapping("/hello")
//read the provided form data
public String display(@RequestParam("name") String name,@RequestParam("pass") String pa
ss,Model m)
{
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
viewpage.jsp
<html>
<body>
${message}
</body>
</html>
errorpage.jsp
<html>
<body>
${message}
<br><br>
<jsp:include page="/index.jsp"></jsp:include>
</body>
</html>
The Spring MVC form tags can be seen as data binding-aware tags that can
automatically set data to Java object/bean and also retrieve from it. Here, each tag
provides support for the set of attributes of its corresponding HTML tag counterpart,
making the tags familiar and easy to use.
1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Syntax
<form:form action="nextFormPath" modelAttribute=?abc?>
Reservation.java
package com.java.model;
public class Reservation {
private String firstName;
private String lastName;
public Reservation()
{
}
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;
}
}
package com.java.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/reservation")
@Controller
public class ReservationController {
@RequestMapping("/bookingForm")
public String bookingForm(Model model)
{
//create a reservation object
Reservation res=new Reservation();
//provide reservation object to the model
model.addAttribute("reservation", res);
return "reservation-page";
}
@RequestMapping("/submitForm")
// @ModelAttribute binds form data to the object
public String submitForm(@ModelAttribute("reservation") Reservation res)
{
return "confirmation-page";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView
Resolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<!DOCTYPE html>
<html>
<head>
<title>Railway Registration Form</title>
</head>
<body>
<a href="reservation/bookingForm">Click here for reservation.</a>
</body>
</html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>Reservation Form</title>
</head>
<h3>Railway Reservation Form</h3>
<body>
<form:form action="submitForm" modelAttribute="reservation">
First name: <form:input path="firstName" />
<br><br>
Last name: <form:input path="lastName" />
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
Note - The value passed with the @ModelAttribute annotation should be the same to
the modelAttribute value present in the view page.
confirmation-page.jsp
<!DOCTYPE html>
<html>
<body>
<p>Your reservation is confirmed successfully. Please, re-check the details.</p>
First Name : ${reservation.firstName} <br>
Last Name : ${reservation.lastName}
</body>
</html>
Syntax
1. <form:radiobutton path="abc" value="xyz"/>
Apart from radio button tag, Spring MVC form tag library also contains radiobuttons tag. This
tag renders multiple HTML input tags with type radio.
1. <form:radiobuttons path="abc" items="${xyz}"/>
package com.java;
public class Reservation {
private String firstName;
private String lastName;
private String Gender;
public Reservation()
{
}
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 String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
}
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/reservation")
@Controller
public class ReservationController {
@RequestMapping("/bookingForm")
public String bookingForm(Model model)
{
//create a reservation object
Reservation res=new Reservation();
//provide reservation object to the model
model.addAttribute("reservation", res);
return "reservation-page";
}
@RequestMapping("/submitForm")
public String submitForm(@ModelAttribute("reservation") Reservation res)
{
return "confirmation-form";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView
Resolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<!DOCTYPE html>
<html>
<head>
<title>Railway Registration Form</title>
</head>
<body>
<a href="reservation/bookingForm">Click here for reservation.</a>
</body>
</html>
7. Create the view components
reservation-page.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>Reservation Form</title>
</head>
<h3>Railway Reservation Form</h3>
<body>
<form:form action="submitForm" modelAttribute="reservation">
First name: <form:input path="firstName" />
<br><br>
Last name: <form:input path="lastName" />
<br><br>
Gender:
Male <form:radiobutton path="Gender" value="Male"/>
Female <form:radiobutton path="Gender" value="Female"/>
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
confirmation-page.jsp
<!DOCTYPE html>
<html>
<body>
<p>Your reservation is confirmed successfully. Please, re-check the details.</p>
First Name : ${reservation.firstName} <br>
Last Name : ${reservation.lastName} <br>
Gender: ${reservation.gender}
</body>
</html>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-
webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
2. Create the bean class
Reservation.java
package com.java;
public class Reservation {
private String firstName;
private String lastName;
private String Gender;
private String[] Food;
private String cityFrom;
private String cityTo;
public Reservation()
{
}
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 String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
public String[] getFood() {
return Food;
}
public void setFood(String[] food) {
Food = food;
}
public String getCityFrom() {
return cityFrom;
}
public void setCityFrom(String cityFrom) {
this.cityFrom = cityFrom;
}
public String getCityTo() {
return cityTo;
}
public void setCityTo(String cityTo) {
this.cityTo = cityTo;
}
}
package com.java;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/reservation")
@Controller
public class ReservationController {
@RequestMapping("/bookingForm")
public String bookingForm(Model model)
{
//create a reservation object
Reservation res=new Reservation();
//provide reservation object to the model
model.addAttribute("reservation", res);
return "reservation-page";
}
@RequestMapping("/submitForm")
public String submitForm(@ModelAttribute("reservation") Reservation res)
{
return "confirmation-page";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
5. Define the bean in the xml file
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<!DOCTYPE html>
<html>
<head>
<title>Railway Registration Form</title>
</head>
<body>
<a href="reservation/bookingForm">Click here for reservation.</a>
</body>
</html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>Reservation Form</title>
</head>
<h3>Railway Reservation Form</h3>
<body>
<form:form action="submitForm" modelAttribute="reservation">
First name: <form:input path="firstName" />
<br><br>
Last name: <form:input path="lastName" />
<br><br>
Gender:
Male<form:radiobutton path="Gender" value="Male"/>
Female<form:radiobutton path="Gender" value="Female"/>
<br><br>
Meals:
BreakFast<form:checkbox path="Food" value="BreakFast"/>
Lunch<form:checkbox path="Food" value="Lunch"/>
Dinner<form:checkbox path="Food" value="Dinner"/>
<br><br>
Leaving from: <form:select path="cityFrom">
<form:option value="Ghaziabad" label="Ghaziabad"/>
<form:option value="Modinagar" label="Modinagar"/>
<form:option value="Meerut" label="Meerut"/>
<form:option value="Amristar" label="Amristar"/>
</form:select>
<br><br>
Going to: <form:select path="cityTo">
<form:option value="Ghaziabad" label="Ghaziabad"/>
<form:option value="Modinagar" label="Modinagar"/>
<form:option value="Meerut" label="Meerut"/>
<form:option value="Amristar" label="Amristar"/>
</form:select>
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
confirmation-page.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<body>
<p>Your reservation is confirmed successfully. Please, re-check the details.</p>
First Name : ${reservation.firstName} <br>
Last Name : ${reservation.lastName} <br>
Gender: ${reservation.gender}<br>
Meals:
<ul>
<c:forEach var="meal" items="${reservation.food}">
<li>${meal}</li>
</c:forEach>
</ul>
Leaving From : ${reservation.cityFrom} <br>
Going To : ${reservation.cityTo}
</body>
</html>
Create a table
Here, we are using emp99 table present in the MySQL database. It has 4 fields: id, name,
salary, and designation. Here, id is auto incremented which is generated by the
sequence.
Create table emp99(id int primary key auto_increment ,name varchar(20),salary double,
designation varchar(20))
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
Emp.java
package com.java.beans;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
package com.java.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.java.beans.Emp;
import com.java.dao.EmpDao;
@Controller
public class EmpController {
@Autowired
EmpDao dao;//will inject dao from XML file
/*It displays a form to input data, here "command" is a reserved request attribu
te
*which is used to display object data into form
*/
@RequestMapping("/empform")
public String showform(Model m){
m.addAttribute("command", new Emp());
return "empform";
}
/*It saves object into database. The @ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
@RequestMapping(value="/save",method = RequestMethod.POST)
public String save(@ModelAttribute("emp") Emp emp){
dao.save(emp);
return "redirect:/viewemp";//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
@RequestMapping("/viewemp")
public String viewemp(Model m){
List<Emp> list=dao.getEmployees();
m.addAttribute("list",list);
return "viewemp";
}
/* It displays object data into form for the given id.
* The @PathVariable puts URL data into variable.*/
@RequestMapping(value="/editemp/{id}")
public String edit(@PathVariable int id, Model m){
Emp emp=dao.getEmpById(id);
m.addAttribute("command",emp);
return "empeditform";
}
/* It updates model object. */
@RequestMapping(value="/editsave",method = RequestMethod.POST)
public String editsave(@ModelAttribute("emp") Emp emp){
dao.update(emp);
return "redirect:/viewemp";
}
/* It deletes record for the given id in URL and redirects to /viewemp */
@RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public String delete(@PathVariable int id){
dao.delete(id);
return "redirect:/viewemp";
}
}
EmpDao.java
package com.java.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.java.beans.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation) values('"+p.getName()
+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary=
"+p.getSalary()+",designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowM
apper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.java.controllers"></
context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolv
er">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataS
ource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></
property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value=""></property>
<property name="password" value=""></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.java.dao.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
<a href="empform">Add Employee</a>
<a href="viewemp">View Employees</a>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Employee</h1>
<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
empeditform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Employee</h1>
<form:form method="POST" action="/SpringMVCCRUDSimple/editsave">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Edit Save" /></td>
</tr>
</table>
</form:form>
viewemp.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefi
x="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</
th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td><a href="editemp/${emp.id}">Edit</a></td>
<td><a href="deleteemp/${emp.id}">Delete</a></td>
</tr>
</c:forEach>
</table>
<br/>
<a href="empform">Add New Employee</a>
As Bean Validation API is just a specification, it requires an implementation. So, for that,
it uses Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309
implementation that allows to express and validate application constraints.
Validation Annotations
Annotation Description
@Min It determines that the number must be equal or greater than the specified value.
@Max It determines that the number must be equal or less than the specified value.
@Size It determines that the size must be equal to the specified value.
@Pattern It determines that the sequence follows the specified regular expression.
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-
validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
package com.java;
import javax.validation.constraints.Size;
public class Employee {
private String name;
@Size(min=1,message="required")
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
package com.java;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EmployeeController {
@RequestMapping("/hello")
public String display(Model m)
{
m.addAttribute("emp", new Employee());
return "viewpage";
}
@RequestMapping("/helloagain")
public String submitForm( @Valid @ModelAttribute("emp") Employee e, Bindi
ngResult br)
{
if(br.hasErrors())
{
return "viewpage";
}
else
{
return "final";
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<a href="hello">Click here...</a>
</body>
</html>
7. Create the other view components
viewpage.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<style>
.error{color:red}
</style>
</head>
<body>
<form:form action="helloagain" modelAttribute="emp">
Username: <form:input path="name"/> <br><br>
Password(*): <form:password path="pass"/>
<form:errors path="pass" cssClass="error"/><br><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>
final.jsp
<html>
<body>
Username: ${emp.name} <br><br>
Password: ${emp.pass}
</body>
</html>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-
validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
package com.java;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
public class Employee {
private String name;
@Size(min=1,message="required")
private String pass;
@Min(value=18, message="must be equal or greater than 18")
@Max(value=45, message="must be equal or less than 45")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.java;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EmployeeController {
@RequestMapping("/hello")
public String display(Model m)
{
m.addAttribute("emp", new Employee());
return "viewpage";
}
@RequestMapping("/helloagain")
public String submitForm( @Valid @ModelAttribute("emp") Employee e, Bindi
ngResult br)
{
if(br.hasErrors())
{
return "viewpage";
}
else
{
return "final";
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.java" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<a href="hello">Click here...</a>
</body>
</html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<style>
.error{color:red}
</style>
</head>
<body>
<form:form action="helloagain" modelAttribute="emp">
Username: <form:input path="name"/> <br><br>
Password: <form:password path="pass"/>
<form:errors path="pass" cssClass="error"/><br><br>
Age: <form:input path="age"/>
<form:errors path="age" cssClass="error"/><br><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>
final.jsp
<html>
<body>
Username: ${param.name} <br>
Password: ${param.pass} <br>
Age: ${param.age } <br>
</body>
</html>