Wednesday, August 6, 2025

[Tips] Spring Boot - Check Out Spring MVC through Implementing a Simple Function

Last updated on:

 

When it comes to Spring MVC, the well-known MVC architecture diagram comes to our mind. It helps us understand how the parts, DispatcherServlet, Controller, Handler, ViewResolver etc, participate into the process of responding to a web request. With Spring Boot, which is characterized with auto-configuration, for example, the web.xml file where we used to configure those web components even is not generated in a Spring Boot Starter project, how does the MVC model work?  

We’re going to check it out by walking through the following example. What will we do? Fetch all the records in the Employees table and display them on a web page. To realize this, we’ll build a Spring web app with a view, a controller, and a model.


Records in Employees


Display on the view


This sample project is available on GitHub.



Prerequisite


Spring Tool Suite is a must have. Assume Eclipse is the development tool. You can go to Eclipse Marketplace, search and get it installed.

The table, Employees, has been created in the database. Here we’re going to use Oracle XE.


SpringMVC project/schema.sql
-- DDL
CREATE TABLE Employees (
   Employee_Id NUMBER(6)
 , First_Name VARCHAR2(20)
 , Last_Name VARCHAR2(20)
 , Salary NUMBER(8)
 , Hire_Date CHAR(10)
 , Manager_Id NUMBER(6)
 , Department_Id NUMBER(4)
)
 NOLOGGING
 PARALLEL;

-- DML
INSERT ALL
 INTO Employees VALUES(100, 'David', 'OConnell', 4800, '2010/01/01', null, 10)
 INTO Employees VALUES(101, 'Susan', 'Grant', 6500, '2010/12/31', 100, 10)
 INTO Employees VALUES(200, 'Jennifer', 'Whalen', 4400, '2010/01/01', null, 20)
 INTO Employees VALUES(201, 'Bruce', 'Hartstein', 6000, '2010/12/31', 200, 20)
 INTO Employees VALUES(202, 'Pat', 'Fay', 6000, '2010/12/31', 200, 20)
SELECT * FROM DUAL;


Create a Spring Boot Web Project


Let’s start with creating a Spring Boot project. 

Click New button, choose Spring Starter Project, as shown in the screenshot below.



Click Next.

Enter a preferred project name. Click Next. 

On the dependencies tab, check Oracle Driver, Spring Data JDBC, Spring Web,  and Thymeleaf. These dependencies will be added into the pom.xml file automatically by the wizard.



Click Finish.



Dependencies


If you prefer to manually manage the dependencies, make sure the following list of libraries is included in pom.xml. 


SpringMVC project/pom.xml
	<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-jdbc</artifactId>
	</dependency>
	<dependency>
		<groupId>com.oracle.database.jdbc</groupId>
		<artifactId>ojdbc11</artifactId>
		<scope>runtime</scope>
	</dependency>


Configure a Data Source


We’ll let Spring Boot to configure the default data source, so we only put down the connection strings in the application property file. This is what they look like.


SpringMVC project/application.properties
spring.config.activate.on-profile=dev
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xepdb1
spring.datasource.username=user
spring.datasource.password=password


Data class


The data retrieved from the Employees table is stored in employee POJOs in the memory. Here is how the class is defined.


SpringMVC project/EmpDto.java
public class EmpDto {
	private Integer employee_id;
	private String first_name;
	private String last_name;
	private Double salary;
	private String hire_date;	
	private Integer manager_id;
	private Long department_id;
	/*
	 * Constructors, Getters, Setters etc.
	 */
	…
}


Controller


A HTTP request eventually comes down to a handler method, where it is processed. The following annotations are used to declare controllers and handler methods.

  • @Controller – declaring a controller
  • @GetMapping – mapping a HTTP GET request to a method (@PostMapping, @PutMapping, @PatchMapping and @DeleteMapping work for the other requests.)


Here’s how the controller and the handler method are defined in this example.

The handler returns a ModelAndView object to the client bearing a logical view name, ”employees”, and an object(Model), a collection of employee POJOs, which is identified by “employees”.


SpringMVC project/EmpController.java
@Controller
public class EmpController{
	
	@Autowired
	private EmpService empService;
		
	@GetMapping(AppConstant.PATH_EMP_FINDALL)
	public ModelAndView findAllEmps(ModelAndView mav) {
		List<EmpDto> emplist = empService.findAll();
		
		mav.setViewName(AppConstant.VIEW_EMPLOYEE);
		mav.addObject("employees", emplist);
	    
		return mav;
	}
}

The constant strings used in the preceding code block are defined as follows.


SpringMVC project/AppConstant.java
public final class AppConstant {
	public static final String VIEW_EMPLOYEE = "employees";
	public static final String PATH_EMP_FINDALL = "/findallemps";
}


Model


Model encapsulates the data. Data doesn’t come from nowhere; therefore, we’d look at it in a broader context here. How the data is processed behind, e.g., business logics involved, is treated as a part of model, conceptually. 

In this project, there is  one more layer in between the service layer and the DAO. For the purpose of demo, we bypass the business logic layer and access the DAO directly from the EmpService bean, so, we can make the program easier to read. 


Service Bean:


SpringMVC project/EmpService.java
@Service
public class EmpService{
	
	@Autowired
	EmpDao empDao;
	
	public List<EmpDto> findAll() {
		return empDao.findAll();
	}
}

DAO:

JDBC is employed to access data in the database. As Spring Boot takes care of the configuration, we can autowire a JdbcTemplate and use it in our DAO.


SpringMVC project/EmpDaoImpl.java
@Repository
public class EmpDaoImpl implements EmpDao {
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	public List<EmpDto> findAll(){
		String sql = "SELECT employee_id, first_name, last_name, salary, "
			+ "hire_date, manager_id, department_id "
			+ "FROM employees "
			+ "ORDER BY employee_id";
        
		return jdbcTemplate.query(sql, new RowMapper<EmpDto>() {
			@Override
			public EmpDto mapRow(ResultSet rs, int rowNum) throws SQLException {
				EmpDto empDto = new EmpDto(
					rs.getInt("employee_id"),
					rs.getString("first_name"),
					rs.getString("last_name"),
					rs.getDouble("salary"),
					rs.getString("hire_date"),
					rs.getInt("manager_id"),
					rs.getLong("department_id"));

				return empDto;
			}
		});	
	};
}


View


The view, employees.html, is the front page presented before users. 

Thymeleaf helps us render the employee list to the view. We include it into the view.

	<html xmlns:th=http://www.thymeleaf.org>

The object returned by the servlet can be accessed with the expression below.

	${employees}

This is what the view’s html looks like.


SpringMVC project/employees.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Spring Web App</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" 
    	rel="stylesheet">
</head>
<body>
	<div class='container outer' style="width: 70%">
	    <h2>Employee Console</h2>
	    <br/>
	    
	    <div class="row">
	    		<table class="table table-hover">
		    		<thead>
				    <tr class="table-primary">
				    	<th scope="col">Employee ID</th>
				    	<th scope="col">First Name</th>
				    	<th scope="col">Last Name</th>
				    	<th scope="col">Salary</th>
				    	<th scope="col">Hire Date</th>
				    	<th scope="col">Manager ID</th>
				    	<th scope="col">Department ID</th>
				    </tr>
			    </thead>
			    <tbody>
				    <tr th:each="employee : ${employees}">
				        <td th:text="${employee.employee_id}">200</td>
				        <td th:text="${employee.first_name}">Susan</td>
				        <td th:text="${employee.last_name}">Grant</td>
				        <td th:text="${employee.salary}">6500</td>
				        <td th:text="${employee.hire_date}">2010/01/01</td>
				        <td th:text="${employee.manager_id}">100</td>
				        <td th:text="${employee.department_id}">10</td>
				    </tr>
			    </tbody>
		    </table>
	    </div>
	    <br/>
	    <div class="row">
	    		<div class="col"></div>
	    		<div class="col"></div>
	    		<div class="col"></div>
	    		<div class="col"></div>
	    		<div class="col"></div>
	    		<div class="col">
	    		<a href="/" class="btn btn-primary" type="button" 
	    			style="width:180px">Back</a>
	    		</div>
	    </div>
	</div>
</body>
</html>


Run the App


We still need an entrance to launch the view. Spring Boot looks for index.html under “static” folder at execution,  so we can embed a link in it. A very simple version can be like this.


index.html
<!DOCTYPE HTML>
<html>
<head> 
<title>Spring Web App</title> 
</head>
<body>
	<h2>Click the link below</h2>
	<br/>
	<div>
	<a href="/findallemps">Show Employees</a>
	</div>
</body>
</html>

After we got index.html in place, launch the web app from Eclipse. 

Enter “localhost:8080” in the browser.

When the index page shows up, click the link. You’ll be directed to the view.




Recap


As a classic pattern for web applications, MVC model has thrived in web app development since it was introduced. It still prevails in this domain. We didn’t delve into the mechanism behind the scene in the demo, instead, our focus was to build a lightweight web app by taking advantage of Spring Boot’s capability, hence we can get a glimpse of the simplicity and productivity that Spring Boot provides.



Reference


[Tips] Spring Boot – Access Data with JDBC



No comments:

Post a Comment

[Tips] Spring Boot - Check Out Spring MVC through Implementing a Simple Function

Last updated on:   When it comes to Spring MVC, the well-known MVC architecture diagram comes to our mind. It helps us underst...