Separating Presentation, Business Logic, and Data Access in Advanced Java
Course: Advanced Java Training
Topic: Separating Presentation, Business Logic, and Data Access
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction
Separating presentation, business logic, and data access is an important software design practice in Advanced Java development. It divides an application into independent layers, with each layer responsible for a specific type of work. This approach is commonly known as layered architecture or three-tier application design.
In a Java web application, the presentation layer handles user interaction, the business logic layer applies application rules, and the data access layer communicates with databases or other data sources. Technologies such as Servlets, JSP, Java classes, JDBC, and the DAO pattern can be used to implement these layers.
When these responsibilities are mixed together, even a small change can affect many parts of an application. Separating them makes the application easier to maintain, test, debug, and extend.
2. Learning Objectives
- Understand the purpose of layered architecture in Java.
- Identify presentation, business logic, and data access responsibilities.
- Understand how Servlets and JSP pages work with service and DAO classes.
- Implement a basic layered application using Java and JDBC.
- Understand the role of MVC, JavaBeans, and the DAO pattern.
- Recognize common design mistakes and apply best practices.
3. What Is Layered Architecture?
Layered architecture organizes application code into logical sections. Each layer has a defined responsibility and communicates with other layers through clearly specified methods or interfaces.
A common flow in an Advanced Java web application is:
Browser
|
v
Presentation Layer
(Servlets, JSP, HTML)
|
v
Business Logic Layer
(Service Classes)
|
v
Data Access Layer
(DAO Classes, JDBC)
|
v
Database
The browser sends a request to the application. A Servlet or controller receives the request and calls the appropriate service. The service applies business rules and uses a DAO to retrieve or update data. The result then returns through the presentation layer to the user.
4. The Three Main Layers
4.1 Presentation Layer
The presentation layer manages communication between the application and the user or client. It receives requests, collects input, coordinates responses, and displays information.
Common technologies:
- HTML and CSS: Structure and style web pages.
- JavaScript: Adds browser-side interaction.
- Servlets: Handle HTTP requests, coordinate application flow, and select responses.
- JSP: Generates dynamic HTML using data supplied by the application.
- JSTL and Expression Language (EL): Help display and format data without embedding large amounts of Java code in JSP pages.
Responsibilities:
- Receive and interpret HTTP requests.
- Collect user input from forms.
- Perform basic input-format checks and coordinate validation.
- Call the appropriate business service.
- Choose the view or response to return.
- Display success messages, errors, and application data.
Example: In an employee management system, a JSP page displays an employee form. A Servlet receives the submitted form and calls the employee service to process the request.
Important: The presentation layer should not contain complex business rules or direct JDBC code. Keeping database queries out of JSP pages and request-handling Servlets makes the application easier to maintain.
4.2 Business Logic Layer
The business logic layer contains the rules and operations that define how the application works. It decides what should happen when a user performs an action.
This layer is commonly implemented using ordinary Java classes called service classes. Depending on the application, it may also use domain objects, JavaBeans, validation components, or transaction-management facilities.
Responsibilities:
- Apply business rules and constraints.
- Validate business conditions.
- Coordinate multiple data operations.
- Calculate values and process application data.
- Decide whether an operation is permitted.
- Manage or participate in transactions where required.
- Call DAO or repository classes to access stored information.
Example: In an employee management application, the service checks that an employee's salary is valid before requesting the DAO to save the employee.
The service should focus on business decisions rather than SQL syntax, HTTP request objects, or HTML formatting.
4.3 Data Access Layer
The data access layer is responsible for communicating with a database or another persistent data source. It hides the details of queries, connections, and data storage from the business logic layer.
Common technologies and patterns:
- JDBC: Connects Java applications to relational databases and executes SQL statements.
- DAO (Data Access Object): Encapsulates database operations in dedicated classes.
- Repository pattern: Provides an abstraction for retrieving and storing domain data.
- JPA and ORM frameworks: Map Java objects to database records in applications that use object-relational persistence.
Responsibilities:
- Insert, retrieve, update, and delete records.
- Execute SQL statements and map results to Java objects.
- Manage database resources appropriately.
- Handle persistence-related errors.
- Keep database-specific implementation details away from business services.
Example: An EmployeeDAO class contains the JDBC code that inserts employee details into an employee table.
5. Comparison of the Three Layers
| Feature |
Presentation Layer |
Business Logic Layer |
Data Access Layer |
| Main purpose |
Manage requests and display information |
Apply business rules and coordinate operations |
Store and retrieve information |
| Typical components |
Servlets, JSP, controllers |
Service classes, domain logic |
DAO, repository, JDBC |
| Works with |
HTTP requests, views, user input |
Business objects and service operations |
Database connections, SQL, result sets |
| Example responsibility |
Receive an employee form |
Check whether employee details meet business rules |
Insert employee details into a table |
| Should avoid |
Complex business rules and SQL queries |
HTML rendering and low-level SQL details |
UI decisions and business workflow rules |
6. Understanding Separation of Concerns
Separation of concerns means organizing code so that each component focuses on a specific responsibility. The three-layer architecture is one practical way to apply this principle.
For example, imagine that an application changes from a JSP-based interface to a REST API. If the business rules are isolated in service classes and database operations are isolated in DAO classes, much of the existing business and persistence code can remain unchanged.
Similarly, if the application moves from one relational database to another, the data access implementation may need to change, but the presentation and business rules should require fewer changes when the layer contracts are designed properly.
7. Relationship Between MVC and Layered Architecture
The Model-View-Controller (MVC) pattern is frequently used with layered architecture in Java web applications. MVC organizes the web interaction into three roles:
- Model: Represents application data and domain behavior. It commonly works with service and data access components.
- View: Displays information to the user, often using JSP.
- Controller: Receives requests, invokes application operations, and selects the response, often using a Servlet.
MVC and layered architecture are related but not identical. MVC focuses on responsibilities in the user-interaction flow, while layered architecture separates responsibilities such as presentation, business rules, and persistence.
Typical Java web application flow:
Browser
|
v
EmployeeServlet (Controller)
|
v
EmployeeService (Business Logic)
|
v
EmployeeDAO (Data Access)
|
v
Database
EmployeeServlet
|
v
employee-list.jsp (View)
|
v
Browser
This arrangement is similar to the MVC Model 2 approach commonly used with Servlets and JSP.
8. Example Project: Employee Management System
Consider an application that allows a user to add an employee. Instead of writing the entire operation in one Servlet, divide it into separate classes.
8.1 Suggested Project Structure
EmployeeManagement/
├── src/main/java/
│ └── com/example/
│ ├── model/
│ │ └── Employee.java
│ ├── dao/
│ │ └── EmployeeDAO.java
│ ├── service/
│ │ └── EmployeeService.java
│ └── controller/
│ └── EmployeeServlet.java
└── src/main/webapp/
└── employee-form.jsp
The package names are illustrative. In a Maven web project, Java classes usually belong under src/main/java and JSP files under src/main/webapp. Configure the servlet mapping and database connection according to the servlet container and database being used.
8.2 Step 1: Create the Model Class
The Employee class represents the employee data handled by the application.
package com.example.model;
public class Employee {
private int id;
private String name;
private double salary;
public Employee() {
}
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
This class holds employee information. It does not render a web page or execute SQL queries. Its purpose is to represent the data used by other layers.
8.3 Step 2: Create the DAO Class
The EmployeeDAO class handles database insertion. This example uses JDBC and a prepared statement to avoid building SQL by concatenating user input.
package com.example.dao;
import com.example.model.Employee;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
public class EmployeeDAO {
private final DataSource dataSource;
public EmployeeDAO(DataSource dataSource) {
this.dataSource = dataSource;
}
public void save(Employee employee) throws SQLException {
String sql =
"INSERT INTO employees (name, salary) VALUES (?, ?)";
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(sql)) {
statement.setString(1, employee.getName());
statement.setDouble(2, employee.getSalary());
statement.executeUpdate();
}
}
}
How it works:
- The DAO receives a configured DataSource through its constructor.
- It obtains a database connection when needed.
- The prepared statement binds the employee name and salary as parameters.
- The insert query is executed.
- The try-with-resources statement closes the connection and statement when the operation completes.
Configuration note: Create the employees table and configure the DataSource for the chosen database and JDBC driver before running this example. A DataSource backed by a connection pool is generally preferable for deployed applications.
8.4 Step 3: Create the Business Service Class
The EmployeeService class checks the business conditions before calling the DAO.
package com.example.service;
import com.example.dao.EmployeeDAO;
import com.example.model.Employee;
import java.sql.SQLException;
public class EmployeeService {
private final EmployeeDAO employeeDAO;
public EmployeeService(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
public void addEmployee(String name, double salary)
throws SQLException {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException(
"Employee name is required."
);
}
if (!Double.isFinite(salary) || salary <= 0) {
throw new IllegalArgumentException(
"Salary must be a positive finite number."
);
}
Employee employee =
new Employee(name.trim(), salary);
employeeDAO.save(employee);
}
}
How it works:
- It receives an EmployeeDAO through constructor injection.
- It checks the name and salary according to the example's business rules.
- It creates an Employee object after validation.
- It calls the DAO to save the data.
In a real application, use appropriate monetary types and precision for salaries, such as BigDecimal, and define domain-specific validation and error-handling rules.
8.5 Step 4: Create the Servlet Controller
The Servlet handles the incoming HTTP request, reads the submitted values, calls the service, and redirects or forwards the user to an appropriate response.
package com.example.controller;
import com.example.service.EmployeeService;
import java.io.IOException;
import java.sql.SQLException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/employees/add")
public class EmployeeServlet extends HttpServlet {
private EmployeeService employeeService;
@Override
public void init() throws ServletException {
// Obtain a configured service from the application's
// dependency-injection or application setup mechanism.
employeeService =
(EmployeeService) getServletContext()
.getAttribute("employeeService");
if (employeeService == null) {
throw new ServletException(
"EmployeeService is not configured."
);
}
}
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String salaryValue = request.getParameter("salary");
try {
if (salaryValue == null ||
salaryValue.trim().isEmpty()) {
throw new IllegalArgumentException(
"Salary is required."
);
}
double salary = Double.parseDouble(salaryValue);
employeeService.addEmployee(name, salary);
response.sendRedirect(
request.getContextPath()
+ "/employee-form.jsp?status=success"
);
} catch (NumberFormatException |
IllegalArgumentException ex) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Please provide a valid employee name and salary."
);
} catch (SQLException ex) {
throw new ServletException(
"Unable to save employee.", ex
);
}
}
}
Implementation notes:
- This example uses the Jakarta Servlet API imports. Older Java EE projects may use
javax.servlet instead of jakarta.servlet; use the package version supported by your server.
- The application must configure and register the
employeeService object in the ServletContext or replace this lookup with a dependency-injection mechanism.
- For a production application, use a dedicated error view, structured logging, and safe user-facing messages instead of exposing internal exception details.
- For applications that perform multiple database changes in one operation, define the transaction boundary deliberately.
8.6 Step 5: Create the JSP Presentation Page
The JSP provides a simple HTML form for submitting employee details. It contains presentation markup rather than database code or business rules.
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Employee</title>
</head>
<body>
<h1>Add Employee</h1>
<form action="${pageContext.request.contextPath}/employees/add"
method="post">
<label for="name">Employee Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="salary">Salary:</label>
<input type="number" id="salary" name="salary"
min="0.01" step="0.01" required>
<br><br>
<button type="submit">Save Employee</button>
</form>
</body>
</html>
The HTML form sends a POST request to the Servlet. The Servlet delegates the operation to the service, which delegates persistence to the DAO.
9. End-to-End Request Flow
- The user opens the employee form in the browser.
- The user enters a name and salary and submits the form.
- The EmployeeServlet receives the POST request.
- The Servlet reads the request parameters and converts the salary into a numeric value.
- The EmployeeService checks the business rules.
- The service creates an Employee object and calls EmployeeDAO.
- The DAO executes the database insert using JDBC.
- The Servlet redirects the user after a successful operation.
- The browser requests the redirected page and displays the response.
This flow demonstrates how each layer performs its own task without taking over the responsibilities of the other layers.
10. Why Use the DAO Pattern?
The Data Access Object pattern provides a dedicated interface between application logic and data storage. It centralizes database operations and hides persistence implementation details from the business layer.
Benefits of DAO:
- Reduced coupling: Service classes do not need to know how SQL queries are executed.
- Maintainability: Database operations can be updated in one place.
- Testability: Services can be tested using a mock or alternative DAO implementation.
- Reusability: Several service methods can use the same DAO methods.
- Portability: Changing the database implementation can be easier when the DAO interface remains stable.
DAO does not automatically make an application database-independent. Database-specific SQL, data types, transaction behavior, and schema differences may still require changes.
11. Using Interfaces to Reduce Coupling
Interfaces can make the boundaries between layers clearer. For example, a service can depend on an EmployeeRepository interface rather than a specific JDBC implementation.
public interface EmployeeRepository {
void save(Employee employee)
throws java.sql.SQLException;
}
The JDBC DAO can implement this interface:
public class EmployeeDAO
implements EmployeeRepository {
// Implement the save method using JDBC.
}
The service can then receive an EmployeeRepository through its constructor. This makes it possible to provide a JDBC implementation in production and a test implementation during unit testing.
12. Testing Each Layer Independently
Separating responsibilities makes testing more focused.
| Layer |
Testing Approach |
Example Test |
| Presentation |
Servlet or web-layer tests |
Verify that invalid request data produces an appropriate response. |
| Business logic |
Unit tests with mocked dependencies |
Verify that a blank employee name is rejected. |
| Data access |
Integration tests against a test database |
Verify that an employee record is inserted correctly. |
Unit tests should cover business rules without requiring a real database wherever possible. DAO integration tests should verify that SQL, schema mappings, and database configuration work correctly.
13. Advantages of Separating the Layers
- Maintainability: Changes can often be isolated to one layer.
- Readability: Classes have clearer responsibilities.
- Testability: Each component can be tested using suitable test methods.
- Reusability: Business services can support different interfaces, such as JSP pages and REST endpoints.
- Scalability: A well-designed application can evolve toward separate deployments if needed.
- Team collaboration: Developers can work on UI, business services, and persistence with clearer boundaries.
- Reduced duplication: Shared rules and database operations can be centralized.
- Improved security practices: Validation, authorization, and database access controls can be implemented in appropriate places.
14. Common Mistakes to Avoid
14.1 Putting SQL in JSP Pages
Embedding JDBC code in JSP pages combines display and persistence responsibilities. Move database operations to DAO classes and display only the data supplied by the application.
14.2 Putting All Logic in a Servlet
A Servlet that validates complex business rules, executes SQL, calculates results, and generates HTML becomes difficult to maintain. Delegate business operations to services and persistence work to DAOs.
14.3 Putting Business Rules in the DAO
The DAO should focus on storing and retrieving data. Rules such as whether an employee is eligible for a particular benefit belong in the business logic layer.
14.4 Duplicating Business Rules
If multiple controllers independently implement the same salary or eligibility rules, they can become inconsistent. Place shared business rules in a service or suitable domain component.
14.5 Ignoring Resource Management
Database connections, statements, and result sets should be closed reliably. Use try-with-resources for JDBC resources and configure connection pooling appropriately for deployed applications.
14.6 Using Unsafe SQL Construction
Do not concatenate untrusted input directly into SQL queries. Use prepared statements with parameters and apply appropriate authorization and validation.
14.7 Exposing Internal Errors
Detailed SQL errors and stack traces should not be shown to end users. Log useful diagnostic information securely and return understandable error messages.
15. Best Practices
- Give every class a clear and focused responsibility.
- Keep JSP pages focused on presentation and use EL/JSTL where appropriate.
- Use Servlets or controllers to handle HTTP request flow.
- Put business rules and workflows in service classes or appropriate domain components.
- Put SQL and persistence-specific code in DAO or repository classes.
- Use constructor injection or a dependency-injection framework to provide dependencies.
- Use interfaces where they create a useful boundary or simplify testing.
- Validate data at appropriate boundaries, and enforce important business rules in the service or domain layer.
- Use prepared statements and manage database transactions correctly.
- Use meaningful package names such as
controller, service, dao, and model.
- Write unit tests for business rules and integration tests for persistence behavior.
- Keep credentials and database configuration outside source code.
16. Layered Architecture vs. Monolithic Design
A monolithic deployment can still use layered architecture. The term monolithic describes how an application is packaged and deployed; layered architecture describes how responsibilities are organized within the code.
For example, a single Java web application deployed to one servlet container can have separate controller, service, and DAO packages. The layers do not need to run on separate machines to provide the benefits of separation of concerns.
As the application grows, its components may later be extracted into separate services, but this should be driven by real requirements rather than assumed to be necessary from the beginning.
17. Practical Exercises
- Create a Product model with product ID, name, and price.
- Create a ProductDAO with methods to insert and retrieve product records.
- Create a ProductService that rejects blank product names and invalid prices.
- Create a Servlet that receives product form submissions and calls the service.
- Create a JSP form to collect product information.
- Test the service with invalid inputs without connecting to a database.
- Change the presentation page without modifying the service or DAO.
- Document which class is responsible for each part of the request flow.
18. Interview Questions and Answers
Q1. What is layered architecture in Java?
Answer: Layered architecture organizes application code into separate responsibilities, such as presentation, business logic, and data access. Each layer communicates through defined interfaces or methods.
Q2. What is the responsibility of the presentation layer?
Answer: It handles user interaction, HTTP requests and responses, and the display of information. In a Servlet/JSP application, Servlets commonly handle requests while JSP pages render views.
Q3. What is the business logic layer?
Answer: It implements application rules and workflows, validates business conditions, coordinates operations, and calls the data access layer when information must be stored or retrieved.
Q4. What is the data access layer?
Answer: It contains code responsible for communicating with data sources. It commonly uses JDBC, DAO classes, repositories, or persistence frameworks.
Q5. What is the DAO pattern?
Answer: DAO stands for Data Access Object. It separates persistence operations from business logic by placing database-specific operations in dedicated classes.
Q6. Why should JDBC code not be placed in JSP pages?
Answer: JDBC code in JSP pages mixes presentation and persistence, makes testing harder, and increases maintenance effort. Database operations should be delegated to DAO or repository classes.
Q7. What is the difference between MVC and layered architecture?
Answer: MVC separates responsibilities related to user interaction into Model, View, and Controller. Layered architecture separates broader application concerns, such as presentation, business rules, and data access. They can be used together.
Q8. Can the layers exist in the same Java project?
Answer: Yes. They can be implemented as separate packages or modules in a single application. Logical separation does not require separate servers.
Q9. How does layered architecture improve testing?
Answer: Each layer can be tested independently. Business services can be tested with mocked DAOs, while DAO implementations can be tested against a test database.
Q10. What happens if business logic is placed in a Servlet?
Answer: The Servlet can become difficult to read and maintain, and business rules may be duplicated across endpoints. Moving those rules to service classes improves reuse and testability.
19. Quick Revision Checklist
- Presentation layer handles user interaction and response rendering.
- Business logic layer applies application rules and coordinates workflows.
- Data access layer performs persistence operations.
- Servlets commonly act as controllers in Java web applications.
- JSP pages are used to render dynamic views.
- Service classes contain business operations.
- DAO classes encapsulate database access.
- MVC can be combined with layered architecture.
- Prepared statements help protect SQL queries from injection.
- Independent layers support maintainability, reuse, and testing.
20. Conclusion
Separating presentation, business logic, and data access is a fundamental practice for building maintainable Advanced Java applications. Servlets and JSP pages can manage the web interaction, service classes can implement business rules, and DAO classes can isolate JDBC operations.
By giving each layer a clear responsibility, developers can make changes more safely, test components independently, and extend an application without unnecessarily affecting unrelated parts. Practicing this architecture through an employee or product management project is an effective way to strengthen Java web development skills.
Explore the Advanced Java Training Course, visit the course demo registration page, or learn more at JustAcademy.