Spring MVC

Sudhanshu Paliwal
6 min readMar 21, 2021

Java is often said to be too complicated and to take too long to build simple applications. Nonetheless, Java provides a stable platform with a very mature ecosystem around it, which makes it a wonderful option for developing robust software.

The Spring Framework, one of the many powerful frameworks in the Java ecosystem, comes with a collection of programming and configuration models with a goal to simplify the development of performant and testable applications in Java.

What is Spring MVCSpring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.

Spring MVC framework is a robust Model view controller framework which helps us to develop a loosely coupled web application. It separates different aspects of web applications with the help of MVC architecture.

Model

Model carries application data. It generally includes POJO in the form of business objects

View

View is used to render User interface (UI). It will render application data on UI. For example JSP

Controller

Controller takes care of processing user request and calling back end services.

Spring MVC WorkFlow

  1. The request will be received by Front Controller i.e. DispatcherServlet.
  2. DispatcherServlet will pass this request to HandlerMapping. HandlerMapping will find suitable Controller for the request
  3. HandlerMapping will send the details of the controller to DispatcherServlet.
  4. DispatcherServlet will call the Controller Spring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.identified by HandlerMapping. The Controller will process the request by calling appropriate method and prepare the data. It may call some business logic or directly retrieve data from the database.
  5. The Controller will send ModelAndView(Model data and view name) to DispatcherServlet.
  6. Once DispatcherServlet receives ModelAndView object, it will pass it to ViewResolver to find appropriate View.
  7. ViewResolver will identify the view and send it back to DispatcherServlet.
  8. Spring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.DispatcherServlet will call appropriate View identified by ViewResolver.
  9. The View will create Response in form of HTML and send it to DispatcherServlet.
  10. DispatcherServlet will send the response to the browser. The browser will render the html code and display it to end user.

Now Let’s develop a demo Spring project using Maven and we will show the files one by one.

pom.xml

POM is an acronym for Project Object Model. The pom.xml file contains information of project and configuration information for the maven to build the project such as dependencies, build directory, source directory, test source directory, plugin, goals etc.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>

Entity Class

To be able to store Point objects in the database using JPA we need to define an entity class. A JPA entity class is a POJO (Plain Old Java Object) class, i.e. an ordinary Java class that is marked (annotated) as having the ability to represent objects in the database. Conceptually this is similar to serializable classes, which are marked as having the ability to be serialized.

@Entity
public class Demo {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String label;
private String description;

public Demo() {
super();
}

public Demo(String label, String description) {
super();
this.label = label;
this.description = description;
}

public long getId() {
return id;
}

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

public String getLabel() {
return label;
}

public void setLabel(String label) {
this.label = label;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

}

Spring Boot JPA

Spring Boot JPA is a Java specification for managing relational data in Java applications. It allows us to access and persist data between Java object/ class and relational database. JPA follows Object-Relation Mapping (ORM). It also provides a runtime EntityManager API for processing queries and transactions on the objects against the database.

JPA Architecture

  • Persistence: It is a class that contains static methods to obtain an EntityManagerFactory instance.
  • EntityManagerFactory: It is a factory class of EntityManager. It creates and manages multiple instances of EntityManager.
  • EntityManager: It is an interface. It controls the persistence operations on objects. It works for the Query instance.
  • Entity: The entities are the persistence objects stores as a record in the database.
  • Persistence Unit: It defines a set of all entity classes. In an application, EntityManager instances manage it. The set of entity classes represents the data contained within a single data store.
  • EntityTransaction: It has a one-to-one relationship with the EntityManager class. For each EntityManager, operations are maintained by EntityTransaction class.
  • Query: It is an interface that is implemented by each JPA vendor to obtain relation objects that meet the criteria.
public interface DemoRepository extends JpaRepository<Skill, Long> {
public List<Skill> findByLabel(String label);
//Your other methods
// You can also Write your own Custom Queries using @Query
annottation.
}

Controller

The @Controllerannotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

@Controller
public class DevelopersController {

@Autowired
DeveloperRepository repository;

@Autowired
SkillRepository skillRepository;

@RequestMapping("/developer/{id}")
public String developer(@PathVariable Long id, Model model) {
model.addAttribute("developer", repository.findOne(id));
model.addAttribute("skills", DemoRepository.findAll());
return "developer";
}

Spring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.@RequestMapping(value="/developers",method=RequestMethod.GET)
public String developersList(Model model) {
model.addAttribute("developers", repository.findAll());
return "developers";
}

@RequestMapping(value="/developers",method=RequestMethod.POST)
public String developersAdd(@RequestParam String email,
@RequestParam String firstName, @RequestParam String lastName, Model model) {
Developer newDeveloper = new Developer();
newDeveloper.setEmail(email);
newDeveloper.setFirstName(firstName);
newDeveloper.setLastName(lastName);
repository.save(newDeveloper);

model.addAttribute("developer", newDeveloper);
model.addAttribute("skills", DemoRepository.findAll());
return "redirect:/developer/" + newDeveloper.getId();
}

Views

All MVC frameworks for web applications provide a way to address views. Spring provides view resolvers, which enable you to render models in a browser without tying you to a specific view technology. Out of the box, Spring enables you to use JSPs, Velocity tempSpring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.lates and XSLT views, for example.

This represents the application’s user interface. View takes model as the input and renders it appropriately to the end user.

Here we are using Thymeleaf to present the view. It is s a template.

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Developers database</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Developers</h1>
<table>
<tr>
<th>Name</th>
<th>Skills</th>
<th></th>
</tr>
<tr th:each="developer : ${developers}">
<td th:text="${developer.firstName + ' ' + developer.lastName}"></td>
<td>
<span th:each="skill,iterStat : ${developer.skills}">
<span th:text="${skill.label}"/><th:block th:if="${!iterStat.last}">,</th:block>
</span>Spring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.
</td>
<td>
<a th:href="@{/developer/{id}(id=${developer.id})}">view</a>
</td>
</tr>
</table>
<hr/>
<form th:action="@{/developers}" method="post" enctype="multipart/form-data">
<div>
First name: <input name="firstName" />
</div>
<div>
Last name: <input name="lastName" />
</div>
<div>
Email: <input name="email" />
</div>
<div>
<input type="submit" value="Create developer" name="button"/>
</div>
</form>
</body>
</html>

Advantage Of Spring MVC

  1. Spring enables the developers to develop enterprise applications using POJOs (Plain Old Java Object). The benefit of developing the applications using POJO is, that we do not need to have an enterprise container such as an application server but we have the option of using a robust servlet container.
  2. Spring gives built in middleware services like Connection pooling, Transaction management and etc.,
  3. Spring provides a light weight container which can be activaed without using webserver or application server.
  4. Spring framework is modular framework and it comes with many modules such as Spring MVC, Spring ORM, Spring JDBC, Spring Transactions etc. which can used as per application requirement in modular fashion.\
  5. Spring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.

--

--