Popular Searches
Popular Course Categories
Popular Courses

Implementing MVC Using Servlets, JSP, and JavaBeans

Implementing MVC Using Servlets, JSP, and JavaBeans

JavaBeans and MVC-Based Web Applications

Implementing MVC Using Servlets, JSP, and JavaBeans

Course: Advanced Java Training

Topic: Implementing MVC Using Servlets, JSP, and JavaBeans

Course Link: Advanced Java Training Course

Demo Link: Register for a Free Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to MVC Architecture

MVC stands for Model-View-Controller. It is a software architectural pattern that separates an application's data and business logic from its user interface and request-handling logic. In Java web development, MVC is commonly implemented using JavaBeans or service classes for the Model, JSP pages for the View, and Servlets for the Controller.

This separation makes web applications easier to develop, test, maintain, and extend. For example, in a student registration application, the Servlet receives registration details, the Model processes and stores the data, and the JSP displays the result.

Why Use MVC?

  • Separation of concerns: Each component has a clearly defined responsibility.
  • Maintainability: Changes to the interface can often be made without changing business logic.
  • Reusability: Model classes can be reused by different views or controllers.
  • Testability: Business logic can be tested independently of JSP pages.
  • Team collaboration: Developers can work on the interface, business logic, and request handling separately.
  • Scalability: A well-organized application is easier to expand as requirements grow.

2. Understanding the Three MVC Components

2.1 Model

The Model represents application data, business rules, and operations. In a Java web application, the Model may include JavaBeans, service classes, DAO classes, and database access logic.

A JavaBean is commonly used to represent data using private fields, a public no-argument constructor, and public getter and setter methods. A JavaBean does not automatically contain all business logic; larger applications usually separate business operations into service classes.

Responsibilities of the Model:

  • Represent and manage application data.
  • Apply business rules and validations.
  • Communicate with repositories or DAO classes when required.
  • Return results to the Controller.
  • Remain independent of presentation details whenever possible.

2.2 View

The View presents information to the user. In traditional Java MVC web applications, JSP is often used as the View. JSP pages can use Expression Language (EL) and JSTL to display data and control simple presentation logic.

Responsibilities of the View:

  • Display data received from the Controller.
  • Render forms, tables, messages, and navigation links.
  • Use EL to access request attributes.
  • Use JSTL for simple presentation conditions and iteration.
  • Avoid database queries and complex business logic.

2.3 Controller

The Controller receives incoming HTTP requests and coordinates the application's workflow. In a traditional Servlet-based MVC application, a Servlet commonly performs this role.

Responsibilities of the Controller:

  • Receive HTTP requests through methods such as doGet() and doPost().
  • Read and validate request parameters.
  • Call appropriate Model or service methods.
  • Store results in request or session attributes when appropriate.
  • Forward the request to a JSP or redirect the browser to another URL.
  • Handle expected errors and choose an appropriate response.

3. Role of Servlets, JSP, and JavaBeans in MVC

Technology MVC Role Typical Responsibility
Servlet Controller Receives requests, coordinates operations, and selects the next view.
JSP View Displays data and provides the user interface.
JavaBean Part of the Model Stores structured application data through properties.
Service Class Model / Business Layer Implements business rules and application operations.
DAO or Repository Data Access Layer Reads and writes data in the database.
Database Persistence Layer Stores application information permanently.

Important: MVC describes the separation of responsibilities. JavaBeans are not automatically the entire Model, and JSP, Servlet, and JavaBean do not have to be the only classes in the application.

4. MVC Request-Response Flow

A typical MVC request follows this sequence:

  1. The user opens a page or submits an HTML form.
  2. The browser sends an HTTP request to a mapped Servlet.
  3. The Servlet reads the request parameters and performs basic input checks.
  4. The Servlet calls a Model or service class.
  5. The Model processes the data and returns a result.
  6. The Servlet places the result in request attributes.
  7. The Servlet forwards the request to the appropriate JSP.
  8. The JSP renders the response and sends HTML back to the browser.
Browser
   |
   | HTTP Request
   v
Servlet Controller
   |
   | Calls business operation
   v
Model / Service / JavaBean
   |
   | Returns result
   v
Servlet Controller
   |
   | RequestDispatcher.forward()
   v
JSP View
   |
   | HTML Response
   v
Browser

5. Project Example: Student Registration Application

In this example, a user enters a student's name and email address. A Servlet receives the form submission, a JavaBean stores the student details, and a JSP displays the result.

5.1 Suggested Project Structure

StudentMVC/
├── src/main/java/
│   └── com/example/
│       ├── model/
│       │   └── Student.java
│       └── controller/
│           └── StudentServlet.java
├── src/main/webapp/
│   ├── index.jsp
│   └── WEB-INF/
│       └── views/
│           └── student-result.jsp
└── pom.xml

This example uses Jakarta Servlet APIs and is intended for a Jakarta EE 9 or later compatible servlet container. Older Java EE applications may use javax.servlet imports instead of jakarta.servlet.

6. Step 1: Create the Student JavaBean

Create a class named Student.java in the com.example.model package. It represents student data and provides getter and setter methods.

package com.example.model;

import java.io.Serializable;

public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private String email;

    public Student() {
    }

    public Student(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Explanation

  • private String name and private String email hold the student's data.
  • The public no-argument constructor supports conventional JavaBean usage.
  • The parameterized constructor allows convenient object creation.
  • Getter methods return property values.
  • Setter methods update property values.
  • Serializable allows the object to participate in Java serialization where needed; it is not mandatory for every JavaBean.

7. Step 2: Create the JSP Registration Form

Create index.jsp in the web application root. This page collects the user's information and submits it to the Servlet.

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Registration</title>
</head>
<body>
    <h1>Student Registration</h1>

    <form action="${pageContext.request.contextPath}/student"
          method="post">
        <label for="name">Student Name:</label>
        <input type="text" id="name" name="name"
               maxlength="100" required>
        <br><br>

        <label for="email">Email Address:</label>
        <input type="email" id="email" name="email"
               maxlength="254" required>
        <br><br>

        <button type="submit">Register</button>
    </form>
</body>
</html>

Explanation

  • The form uses the HTTP POST method to submit data.
  • The action points to the /student Servlet mapping.
  • The name and email attributes become request parameter names.
  • The application context path is included so the form works when the application is deployed under a non-root context.
  • Browser-side attributes such as required improve usability, but server-side validation is still necessary.

8. Step 3: Create the Servlet Controller

Create StudentServlet.java in the com.example.controller package. The Servlet validates basic input, creates a Student object, adds it to the request, and forwards the request to the JSP view.

package com.example.controller;

import com.example.model.Student;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.regex.Pattern;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private static final Pattern EMAIL_PATTERN =
        Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String email = request.getParameter("email");

        if (name == null || email == null
                || name.trim().isEmpty()
                || email.trim().isEmpty()) {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Name and email are required."
            );
            return;
        }

        name = name.trim();
        email = email.trim();

        if (name.length() > 100 || email.length() > 254
                || !EMAIL_PATTERN.matcher(email).matches()) {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Please enter valid registration details."
            );
            return;
        }

        Student student = new Student(name, email);

        request.setAttribute("student", student);

        request.getRequestDispatcher(
            "/WEB-INF/views/student-result.jsp"
        ).forward(request, response);
    }
}

Explanation

  • @WebServlet("/student") maps the URL to the Servlet.
  • doPost() handles form submissions using HTTP POST.
  • request.getParameter() retrieves submitted form values.
  • Basic validation rejects missing or excessively long values and checks the email's general format.
  • new Student(name, email) creates the Model object.
  • request.setAttribute() makes the object available to the JSP during the same request.
  • RequestDispatcher.forward() transfers processing to the JSP without sending a new browser request.
  • The JSP is placed inside WEB-INF so users cannot request it directly by its path.

Note: The email pattern is a basic example, not a complete email-address validator. Real applications should use appropriate validation rules and apply business-specific checks in the service layer.

9. Step 4: Create the JSP Result View

Create student-result.jsp under WEB-INF/views. This JSP displays the data provided by the Servlet.

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration Result</title>
</head>
<body>
    <h1>Registration Submitted</h1>

    <p>Student Name:
        <span>${student.name}</span>
    </p>

    <p>Email Address:
        <span>${student.email}</span>
    </p>

    <p>Your details passed the example validation checks.</p>

    <a href="${pageContext.request.contextPath}/index.jsp">
        Register Another Student
    </a>
</body>
</html>

How It Works

  • ${student.name} accesses the JavaBean's name property through Expression Language.
  • ${student.email} accesses the email property.
  • The JSP focuses on displaying the result rather than processing the registration workflow.

Security note: EL output is not automatically HTML-escaped in every JSP configuration. For production applications, encode user-supplied values for the HTML context using a trusted output-encoding library or an appropriate escaping tag. Do not assume that validation alone prevents cross-site scripting (XSS).

10. Understanding Request Attributes and Scope

Servlets and JSP pages need a way to share data. The correct scope depends on how long the data must remain available.

Scope Lifetime Typical Use
Page Within a JSP page Temporary values used by a JSP.
Request During one HTTP request, including a forward Form results, validation messages, and data for the next JSP.
Session Across multiple requests in one user session Authenticated user context and short-lived user-specific state.
Application For the lifetime of the web application Shared application-wide data that is safe to share.

For the registration example, request scope is appropriate because the student object is needed only to render the result page for the current request.

// In the Servlet
request.setAttribute("student", student);

// In the JSP
${student.name}

11. Request Forwarding vs. Redirecting

Forwarding and redirecting are different navigation techniques and should be selected according to the workflow.

Feature Forward Redirect
Mechanism Server-side transfer using RequestDispatcher Browser receives a redirect response and sends another request
Browser URL Usually remains the original URL Changes to the redirect destination
Request attributes Remain available during the forward Do not automatically carry over to the new request
Typical use Display a result or validation errors Navigate after a successful state-changing operation

Forward Example

request.setAttribute("message", "Please review your details.");
request.getRequestDispatcher("/WEB-INF/views/form.jsp")
       .forward(request, response);

Redirect Example

response.sendRedirect(
    request.getContextPath() + "/students"
);

A common production pattern is Post/Redirect/Get (PRG): after a successful POST that creates or updates data, redirect the browser to a GET endpoint. This reduces accidental resubmission when the user refreshes the result page. If data must be shown after the redirect, retrieve it again using an identifier or use a carefully designed flash-message mechanism.

12. Improving MVC with Service and DAO Layers

For a small demonstration, a Servlet may create a JavaBean directly. In a larger application, keep business logic and persistence operations out of the Servlet. Use a service layer for business rules and a DAO or repository layer for database access.

Browser
   |
   v
Servlet Controller
   |
   v
StudentService
   |
   v
StudentDAO
   |
   v
Database

Example Service Class

package com.example.service;

import com.example.model.Student;

public class StudentService {

    public Student createStudent(String name, String email) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException(
                "Student name is required."
            );
        }

        if (email == null || email.trim().isEmpty()) {
            throw new IllegalArgumentException(
                "Student email is required."
            );
        }

        // A real application can call a DAO here
        // to persist the student in a database.
        return new Student(name.trim(), email.trim());
    }
}

This service is only an illustrative starting point. In a real application, the service should apply all relevant business rules, while the DAO should handle database operations using prepared statements or an appropriate persistence framework.

Why Use a DAO?

  • Separates SQL and database operations from request handling.
  • Makes persistence code easier to test and maintain.
  • Allows database implementation details to change with less impact on the controller.
  • Encourages reusable data access methods.

13. Validation and Error Handling

Validation should occur at appropriate layers. Client-side checks improve the user experience, while server-side checks protect the application because clients can bypass browser validation.

  • Input validation: Check required values, lengths, formats, and allowed ranges.
  • Business validation: Check application rules, such as whether an email is already registered.
  • Persistence validation: Enforce database constraints, including unique keys and not-null rules.
  • Error messages: Display helpful messages without exposing stack traces, SQL statements, or internal implementation details.
  • Logging: Record technical failures securely on the server while returning safe messages to users.

For a production application, map validation exceptions to the appropriate view or error response rather than allowing unexpected exceptions to produce unhandled server errors.

14. Security Best Practices for MVC Applications

  • Use HTTPS to protect data in transit.
  • Validate all untrusted input on the server.
  • Use context-appropriate output encoding to prevent XSS.
  • Use prepared statements or parameterized persistence APIs to reduce SQL injection risks.
  • Apply authentication and authorization checks in the controller and service layers as appropriate.
  • Protect state-changing requests against cross-site request forgery (CSRF).
  • Do not store passwords as plain text; use a suitable password-hashing algorithm if managing credentials.
  • Keep configuration secrets outside source code.
  • Do not expose JSP pages that should only be reached through a controller; placing them under WEB-INF helps enforce this design.
  • Set secure session-cookie options and invalidate sessions when appropriate.

15. Common Mistakes and Troubleshooting

Problem Possible Cause Solution
404 Not Found Incorrect Servlet mapping or context path. Check @WebServlet, deployment context, and form action.
405 Method Not Allowed The form uses POST but the Servlet only implements GET, or vice versa. Implement the appropriate HTTP method and verify the form method.
Null value in JSP The request attribute was not set or its name differs. Check the exact attribute name and ensure the forward occurs after setting it.
JSP cannot access a property Missing or incorrectly named getter method. Confirm JavaBean property names and public getter methods.
JSP shows no result after redirect Request attributes are lost on the new request. Retrieve data again or use a suitable flash-message mechanism.
Compilation error for Servlet imports Servlet API namespace does not match the target container. Use jakarta.servlet for compatible newer containers or javax.servlet for older Java EE containers.
Character encoding problems Request encoding is set too late or is inconsistent. Set request encoding before reading POST parameters and configure page encoding consistently.
User input appears as HTML Output is rendered without context-appropriate encoding. Use a trusted HTML output-encoding approach.

16. Best Practices for Writing Maintainable MVC Code

  • Keep Servlets focused on HTTP request and response handling.
  • Keep JSP pages focused on presentation, not database operations.
  • Use JavaBeans to represent structured data and service classes for business rules.
  • Use DAO or repository classes to isolate persistence code.
  • Use meaningful names for Servlet mappings, classes, attributes, and methods.
  • Prefer request scope for data used by one request; avoid unnecessary session or application scope.
  • Use POST for state-changing form submissions and consider PRG after success.
  • Centralize exception handling and logging where practical.
  • Write unit tests for business logic and integration tests for database operations.
  • Keep dependencies and framework versions compatible with the target Servlet container.

17. Practical Exercises

Exercise 1: Add a Student ID

Add a student ID field to the JavaBean and registration form. Validate the value in the Servlet and display it on the result JSP.

Exercise 2: Display Validation Errors

Instead of returning an HTTP error for every invalid field, place safe validation messages in request attributes and forward to a JSP form that displays the messages.

Exercise 3: Add a Service Layer

Move registration rules from the Servlet to a StudentService class. Make the Servlet call the service and handle expected validation exceptions.

Exercise 4: Connect a Database

Create a StudentDAO that saves student information in a relational database. Use parameterized SQL, close resources reliably, and handle duplicate email addresses.

Exercise 5: Build a Student Listing Page

Create a controller endpoint that retrieves students from the service, places a collection in a request attribute, and forwards it to a JSP. Use JSTL to iterate over the list and encode displayed user data safely.

18. Interview Questions and Answers

Q1. What is MVC in Java web development?

Answer: MVC is an architectural pattern that separates the Model, View, and Controller. In a traditional Servlet/JSP application, the Model represents data and business operations, JSP presents information, and Servlets handle requests and coordinate the workflow.

Q2. Why is a Servlet used as a Controller?

Answer: A Servlet receives HTTP requests, reads parameters, calls application logic, sets attributes, and forwards or redirects to the appropriate destination.

Q3. What is the role of JSP in MVC?

Answer: JSP generates the user-facing HTML response. It can use Expression Language and JSTL to display data and perform simple presentation tasks.

Q4. What is a JavaBean?

Answer: A JavaBean is a Java class that follows conventional component patterns, commonly including private properties, a public no-argument constructor, and public getter and setter methods. Serializable support is often used but is not universally required.

Q5. How does a Servlet pass data to a JSP?

Answer: The Servlet can call request.setAttribute("key", value) and forward the request to a JSP. The JSP can then access the value through EL, such as ${key}.

Q6. What is the difference between request parameters and request attributes?

Answer: Request parameters usually come from the client, such as form fields or query strings. Request attributes are server-side objects added by application code and are available within the same request, including during a forward.

Q7. Why should JSP pages be placed under WEB-INF?

Answer: A JSP under WEB-INF cannot be accessed directly by a normal browser URL. The application can forward to it through a Servlet, helping enforce controller-based navigation.

Q8. What is the difference between forward and redirect?

Answer: A forward transfers processing on the server within the same request. A redirect instructs the browser to make a new request, changing the URL and not automatically preserving request attributes.

Q9. Should SQL queries be written inside a JSP?

Answer: No. Database operations should be placed in a DAO or repository layer and coordinated through business services and controllers. This separation improves security, testing, and maintainability.

Q10. What is the Post/Redirect/Get pattern?

Answer: PRG redirects the browser after a successful POST so that refreshing the resulting GET page is less likely to repeat the original form submission.

Q11. How can an MVC application prevent SQL injection?

Answer: Use parameterized SQL through JDBC prepared statements or a suitable persistence framework. Avoid building SQL by concatenating untrusted input.

Q12. What is the benefit of a service layer?

Answer: It centralizes business rules and application operations outside the Servlet, allowing the logic to be reused and tested independently of HTTP handling.

19. Quick Revision Checklist

  • MVC means Model-View-Controller.
  • Servlets commonly act as Controllers.
  • JSP pages commonly act as Views.
  • JavaBeans can represent Model data.
  • Service classes contain business operations.
  • DAO or repository classes manage persistence.
  • Request attributes can share data with a JSP during a forward.
  • Redirects start a new browser request.
  • Server-side validation is essential.
  • Output encoding and parameterized database access help protect against common vulnerabilities.
  • JSP pages under WEB-INF can be reached through server-side forwarding.

20. Conclusion

Implementing MVC using Servlets, JSP, and JavaBeans provides a structured foundation for traditional Java web applications. Servlets coordinate HTTP requests, JavaBeans represent application data, and JSP pages render the response. Adding service and DAO layers makes the design more maintainable as the application grows.

Practice by building a registration form, validating input, passing a Model object to a JSP, and then extending the project with a database and service layer. Focus on separation of concerns, clear request flow, secure output handling, and reliable error management.

Related Learning Resources

Previous Next
whatsapp