Spring MVC

surya mdl
2 min readMar 22, 2021

A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern.

Path of process
  • Model — A model contains the data of the application. A data can be a single object or a collection of objects
  • Controller — A controller contains the business logic of an application.
  • View — A view represents the provided information in a particular format.

When a request is sent to browser,the pattern of the URL gets checked with the controller methods url and the matching controller method gets executed and controller method returns the either view page or redirect to another controller method.

The data is passed from controller to view or between controllers is by model.

Here Thymeleaf is used to access the data in the model in HTML pages.

There are many annotations used which reduces the work of configuring in xml file .

Some annotations are listed below

@Controller: This annotation is used to specify that class is controller.

@RequestMapping: This annotation is used with controller classes to check the controller method url with request url.

@GetMapping: This annotation is used with controller methods for the requests to retrieve data from database.

@PostMapping:This annotation is used with controller methods for the requests to post the data into database.

@RequestParam: This annotation is used to retrieve value from thymeleaf page to controller method

@ModelAttribute:This annotation is used to retrieve data from model .

@Autowired: This annotation is used for dependency injection to inject the classes that implements the interface (method parameter)

@Entity : This annotation is used to map a class and a table in database.

@Column: This annotation is used to map column in a table in database with field in entity class.

@Id : This annotation is used to specify that field in entity class is primary key.

Example of controller

@Controller
public class SampleController {
@GetMapping("/sample")
public String showForm() {
return "sample";
}

}

As controller returns view page here in this example sample is an html page.

<html>
<head></head>

<body>
<h1>This is the body of the sample view</h1>
</body>
</html>
  • CRUD operations on database can be done by using spring mvc without hardcoding.

Advantages of Spring MVC

  • The Spring MVC separates each role, where the model object, controller, command object, view resolver, DispatcherServlet, validator, etc. can be fulfilled by a specialized object.
  • In Spring, generally we create JavaBeans classes that enable you to inject test data using the setter methods.
  • It provides the specific annotations that easily redirect the page.

--

--