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.
Steps:
o Load the spring jar files or add dependencies in the case of Maven
o Create the controller class
o Provide the entry of controller in the web.xml file
o Define the bean in the separate XML file
o Display the message in the JSP page
o Start the server and deploy the project
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
</beans>
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";
}
}
}
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>
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 pass,M
odel 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";
}
}
}
Syntax
<form:form action="nextFormPath" modelAttribute=?abc?>
@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";
}
}
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}"/>
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;
}
}
@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";
}
}
package com.java;
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";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Railway Registration Form</title>
</head>
<body>
<a href="reservation/bookingForm">Click here for reservation.</a>
</body>
</html>
confirmation-page.jsp
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))
Emp.java
package com.java.beans;
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 attribute
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;
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
empeditform.jsp
<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
<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>D
elete</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>
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.
package com.java;
import javax.validation.constraints.Size;
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, BindingRe
sult br)
{
if(br.hasErrors())
{
return "viewpage";
}
else
{
return "final";
}
}
}
final.jsp
<html>
<body>
Username: ${emp.name} <br><br>
Password: ${emp.pass}
</body>
</html>
o @Min annotation - It is required to pass an integer value with @Min annotation. The
user input must be equal to or greater than this value.
o @Max annotation - It is required to pass an integer value with @Max annotation.
The user input must be equal to or smaller than this value.
package com.java;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
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, BindingRe
sult br)
{
if(br.hasErrors())
{
return "viewpage";
}
else
{
return "final";
}
}
}
final.jsp
<html>
<body>
Username: ${param.name} <br>
Password: ${param.pass} <br>
Age: ${param.age } <br>
</body>
</html>