Building Dynamic Web Applications Using Servlets
Course: Advanced Java Training
Topic: Building Dynamic Web Applications Using Servlets
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to Dynamic Web Applications
A dynamic web application is a software application that generates or modifies its content based on user input, database records, authentication status, business rules, or other runtime information. Unlike a static website, which primarily serves predefined files, a dynamic application can produce different responses for different requests.
Java Servlets are server-side Java components used to build dynamic web applications. They receive HTTP requests, process input, interact with application services or databases, and generate HTTP responses. A servlet container such as Apache Tomcat manages the servlet lifecycle and routes incoming requests to the appropriate servlet.
Servlets are commonly used to implement login systems, registration forms, search pages, student management applications, product catalogs, employee portals, and other web-based systems.
Example of Dynamic Content
Consider a student portal. When a student logs in, the application retrieves the student's details and displays a personalized dashboard. Another student may see a different dashboard because the response depends on the authenticated user's information.
This type of runtime content generation is one of the main purposes of servlet-based web development.
2. Learning Objectives
After completing this topic, you should be able to:
- Understand the architecture of a dynamic web application.
- Explain the role of Java Servlets in server-side processing.
- Create servlets using the
HttpServlet class.
- Handle HTTP GET and POST requests.
- Read request parameters and generate responses.
- Connect servlets with Java service and DAO classes.
- Retrieve and display data from a database using JDBC.
- Understand request forwarding, redirection, sessions, and application scope.
- Organize web application code using a simple MVC architecture.
- Deploy and test a servlet-based application on Apache Tomcat.
- Apply validation, security, and error-handling practices.
3. Static Websites vs Dynamic Web Applications
| Feature |
Static Website |
Dynamic Web Application |
| Content |
Primarily predefined files |
Generated or updated using application logic and data |
| User interaction |
Usually limited to navigation and client-side behavior |
Can process forms, authentication, searches, and transactions |
| Database integration |
Not generally required |
Often uses a database or external service |
| Personalization |
Limited without additional technology |
Can display user-specific information |
| Processing |
Primarily serves existing resources |
Runs server-side logic for requests |
| Examples |
Basic informational page |
Student portal, shopping website, employee management system |
4. Role of Servlets in Web Application Development
A servlet acts as a server-side component between the client and the application's business logic. It receives request information, invokes the required operations, and returns a response or passes control to another web component.
Main Responsibilities of a Servlet
- Receive HTTP requests from browsers or other clients.
- Read form fields, query parameters, and request headers.
- Validate request data before processing.
- Call service classes to perform business operations.
- Retrieve or update data through a DAO or repository layer.
- Store suitable information in request or session attributes.
- Forward a request to a view or redirect the client to another URL.
- Return HTML, JSON, plain text, or another appropriate response format.
For maintainable applications, servlets should generally coordinate request processing rather than contain all business rules, database code, and HTML generation in one class.
5. Architecture of a Servlet-Based Web Application
A typical servlet application contains the following layers:
- Presentation layer: HTML forms, CSS, JavaScript, and view templates.
- Controller layer: Servlets that receive requests and decide what operation should run.
- Service layer: Java classes containing business rules and application workflows.
- DAO layer: Classes responsible for database access through JDBC or another persistence technology.
- Database layer: Stores application data such as users, students, products, or orders.
Request Processing Flow
Browser
|
| HTTP Request
v
Servlet Container (Apache Tomcat)
|
v
Servlet Controller
|
v
Service Layer
|
v
DAO / Repository
|
v
Database
|
| Query Result
v
Service Layer
|
v
Servlet Controller
|
v
HTML / JSON Response
|
v
Browser
This layered design separates user-interface handling, business rules, and data access. It makes the application easier to test, maintain, and extend.
6. Understanding HttpServlet
The HttpServlet class is part of the Servlet API and is commonly extended when building applications that communicate over HTTP. It provides handler methods for HTTP request methods such as GET and POST.
A servlet typically overrides one or more of the following methods:
| Method |
Purpose |
Typical Use |
doGet() |
Handles HTTP GET requests |
Displaying records or search results |
doPost() |
Handles HTTP POST requests |
Submitting forms or creating records |
doPut() |
Handles HTTP PUT requests |
Updating a resource through an HTTP API |
doDelete() |
Handles HTTP DELETE requests |
Deleting a resource through an HTTP API |
init() |
Initializes the servlet |
Performing setup required for the servlet lifecycle |
destroy() |
Called when the servlet is taken out of service |
Releasing servlet-owned resources |
7. Creating a Basic Dynamic Web Application
The following example creates a simple servlet that generates a response based on a request parameter. It uses the Jakarta Servlet API, suitable for compatible servlet containers such as Tomcat 10 or later.
Example 1: GreetingServlet.java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/greeting")
public class GreetingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String name = request.getParameter("name");
if (name == null || name.isBlank()) {
name = "Guest";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang='en'>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>Greeting Application</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Welcome to the Dynamic Web Application</h1>");
out.println("<p>Your request was processed successfully.</p>");
out.println("</body>");
out.println("</html>");
}
}
Explanation:
@WebServlet("/greeting") maps the servlet to the /greeting URL pattern.
doGet() processes GET requests.
request.getParameter("name") reads the submitted query parameter.
- The servlet applies a default value when the parameter is missing.
response.setContentType() identifies the response as UTF-8 HTML.
- The servlet returns HTML content to the browser.
Example URL:
http://localhost:8080/MyWebApp/greeting?name=Student
Replace MyWebApp with your actual application context path. This simple example reads the parameter but does not display it in the HTML output. If you later display user-supplied content, escape it using a trusted HTML-escaping utility to prevent cross-site scripting.
8. Handling User Input with HTML Forms
HTML forms allow users to submit information to a servlet. The form's action attribute identifies the destination, while its method attribute specifies how the request is sent.
Example 2: Student Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Details</title>
</head>
<body>
<h1>Enter Student Details</h1>
<form action="student" method="post">
<label for="studentName">Student Name:</label>
<input type="text"
id="studentName"
name="studentName"
required>
<br><br>
<label for="course">Course:</label>
<input type="text"
id="course"
name="course"
required>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
The browser sends a POST request to the servlet mapped to /student. The servlet reads the fields by their name attributes.
Example 3: StudentServlet.java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
request.setCharacterEncoding("UTF-8");
String studentName = request.getParameter("studentName");
String course = request.getParameter("course");
if (studentName == null || studentName.isBlank()
|| course == null || course.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Student name and course are required."
);
return;
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h2>Student Form Submitted</h2>");
out.println("<p>Your information passed basic validation.</p>");
out.println("</body></html>");
}
}
This example validates the presence of the fields. A complete application should also apply business validation, escape any user-supplied content that is rendered, and save data through an appropriate service or DAO layer when persistence is required.
9. Generating Dynamic Content
Dynamic content is produced when the response depends on request data, session information, database records, or application logic.
Common Examples
- Displaying a greeting based on a submitted name.
- Showing products that match a search query.
- Displaying student records retrieved from a database.
- Showing a personalized dashboard after authentication.
- Returning an error message when input validation fails.
- Producing JSON for a client-side application.
For larger applications, use JSP or another suitable view technology for HTML presentation instead of constructing complex HTML through many Java output statements.
10. Connecting Servlets to a Database Using JDBC
Dynamic applications often retrieve or store data in a database. Java Database Connectivity (JDBC) provides APIs for communicating with relational databases.
A recommended design is to keep database operations in a DAO class rather than writing SQL directly inside a servlet.
Example: Student Model
package com.example.model;
public class Student {
private final int id;
private final String name;
private final String course;
public Student(int id, String name, String course) {
this.id = id;
this.name = name;
this.course = course;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getCourse() {
return course;
}
}
Example: StudentDAO.java
package com.example.dao;
import com.example.model.Student;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
public class StudentDAO {
private final DataSource dataSource;
public StudentDAO(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Student> findAll() throws SQLException {
String sql =
"SELECT id, name, course FROM students ORDER BY id";
List<Student> students = new ArrayList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
Student student = new Student(
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("course")
);
students.add(student);
}
}
return students;
}
}
Important: This DAO example uses a configured DataSource, which must be provided by the application's configuration or dependency injection setup. The example assumes a table named students with columns id, name, and course. The model, DAO, and servlet must be compiled and packaged together with the appropriate database driver.
Why Use PreparedStatement?
- It separates SQL structure from parameter values.
- It helps prevent SQL injection when values are bound correctly.
- It supports clear and maintainable database code.
- It can support database statement reuse and efficient execution.
11. Using a Servlet to Display Database Records
A servlet can retrieve records through a service or DAO and then pass the results to a view. The following example illustrates the controller flow. It assumes a StudentService class exists and provides a findAll() method returning a list of students.
package com.example;
import com.example.model.Student;
import com.example.service.StudentService;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
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("/students")
public class StudentListServlet extends HttpServlet {
private StudentService studentService;
@Override
public void init() throws ServletException {
// In a complete application, obtain this service
// through dependency injection or application configuration.
studentService = (StudentService) getServletContext()
.getAttribute("studentService");
if (studentService == null) {
throw new ServletException(
"StudentService has not been configured."
);
}
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
List<Student> students = studentService.findAll();
request.setAttribute("students", students);
request.getRequestDispatcher("/WEB-INF/students.jsp")
.forward(request, response);
} catch (SQLException exception) {
throw new ServletException(
"Unable to retrieve student records.", exception
);
}
}
}
This controller example assumes that the service is configured as a servlet-context attribute and that a JSP view exists at /WEB-INF/students.jsp. The application must initialize the service and its DAO before requests are processed. The JSP should use an appropriate escaping mechanism when rendering student data.
12. Understanding Request Forwarding
Request forwarding allows a servlet to transfer control to another server-side resource, such as a JSP page. The forwarded resource processes the same request and can access request attributes set by the servlet.
request.setAttribute("message", "Student records loaded");
request.getRequestDispatcher("/WEB-INF/students.jsp")
.forward(request, response);
Key Points
- The forward happens on the server.
- The browser's address bar normally remains unchanged.
- Request attributes are available to the forwarded resource.
- The response must not already be committed in a way that prevents forwarding.
- Placing JSP files under
WEB-INF prevents direct browser access to those files.
13. Understanding Redirects
A redirect instructs the browser to make a new request to another URL. It is commonly used after successful form submissions.
response.sendRedirect(
request.getContextPath() + "/students"
);
Redirects are useful when applying the Post/Redirect/Get pattern. After a POST creates or updates data, the server redirects the browser to a GET endpoint. This reduces duplicate form submissions when users refresh the result page.
| Feature |
Forward |
Redirect |
| Execution |
Server-side transfer |
Browser makes a new request |
| Browser URL |
Usually unchanged |
Changes to the destination URL |
| Request attributes |
Remain available to the forwarded resource |
Not automatically preserved in the new request |
| Typical use |
Pass request data to a view |
Navigate after a successful operation |
14. Managing User Sessions
HTTP is stateless, meaning each request is independent at the protocol level. A web application can use an HTTP session to maintain information associated with a user's interaction across multiple requests.
Example: Storing a Session Attribute
import jakarta.servlet.http.HttpSession;
// Inside a servlet request handler:
HttpSession session = request.getSession();
session.setAttribute("username", "student");
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Session information stored.");
Reading a Session Attribute
HttpSession session = request.getSession(false);
if (session != null) {
Object username = session.getAttribute("username");
// Verify authentication and authorization as needed.
}
Do not treat the existence of a session attribute alone as sufficient proof of authorization. Validate the user's identity and permissions before allowing access to protected operations.
15. Organizing a Servlet Application with MVC
MVC stands for Model-View-Controller. It is an architectural pattern that separates application data, presentation, and request-handling logic.
| Component |
Responsibility |
Example |
| Model |
Represents application data |
Student.java |
| View |
Displays information to the user |
students.jsp |
| Controller |
Handles requests and coordinates processing |
StudentListServlet.java |
| Service |
Implements business operations |
StudentService.java |
| DAO |
Handles data persistence |
StudentDAO.java |
Benefits of MVC
- Improves separation of concerns.
- Reduces duplicated code.
- Makes unit testing easier.
- Allows presentation changes without rewriting database logic.
- Supports future expansion of the application.
16. Handling Errors and Exceptions
Dynamic applications must handle invalid input, database failures, unavailable services, and unexpected programming errors.
Common Error-Handling Techniques
- Validate required parameters before processing a request.
- Return an appropriate status code for invalid requests.
- Log technical details on the server for debugging.
- Display a user-friendly error page rather than raw stack traces.
- Use try-with-resources for JDBC connections, statements, and result sets.
- Handle expected business errors separately from unexpected system failures.
Example: Returning a Bad Request
String email = request.getParameter("email");
if (email == null || email.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Email is required."
);
return;
}
Do not expose database credentials, stack traces, SQL statements, or internal server details in responses sent to ordinary users.
17. Security Best Practices for Servlet Applications
- Use HTTPS: Protect data while it travels between the client and server.
- Validate input: Apply server-side validation to all client-provided values.
- Escape output: Prevent untrusted data from being interpreted as executable HTML or JavaScript.
- Prevent SQL injection: Use prepared statements and parameter binding for database queries.
- Protect against CSRF: Use appropriate CSRF protection for state-changing operations in authenticated browser applications.
- Enforce authorization: Verify that the current user is allowed to access the requested records and operations.
- Store passwords safely: Use a suitable password-hashing algorithm through a trusted security library; never store plain-text passwords.
- Protect session cookies: Configure suitable Secure, HttpOnly, and SameSite attributes according to the application's requirements.
- Keep configuration private: Do not hardcode production passwords or API keys in source code.
- Write thread-safe servlets: Avoid shared mutable request-specific data in servlet instance fields.
- Limit data exposure: Return only the information the client needs.
18. Common Problems and Troubleshooting
| Problem |
Possible Cause |
Solution |
| 404 Not Found |
Incorrect context path or servlet mapping |
Verify the deployed application name and URL pattern. |
| 405 Method Not Allowed |
Unsupported HTTP method |
Implement the required handler and submit the correct request method. |
| Request parameter is null |
Incorrect form field name or missing submission |
Match the HTML name attribute with the parameter key. |
| Database connection failure |
Incorrect configuration, unavailable database, or missing driver |
Verify the database service, credentials, driver, and connection pool settings. |
| 500 Internal Server Error |
Unhandled exception or server-side failure |
Inspect application logs and correct the underlying issue. |
| JSP not found |
Incorrect view path or missing JSP file |
Verify the view location and request dispatcher path. |
| Incorrect characters |
Encoding mismatch |
Use UTF-8 consistently for requests, responses, and HTML pages. |
| Duplicate form submission |
User refreshes or resubmits the POST request |
Use Post/Redirect/Get and appropriate idempotency controls. |
| Data leakage between requests |
Request-specific values stored in shared servlet fields |
Use local variables and request-scoped data instead. |
19. Mini Project: Student Management Web Application
Project Objective: Build a dynamic web application that lets users view, register, and manage student records using Java Servlets.
Functional Requirements
- Display a student registration form.
- Accept student name, email, and course information.
- Validate the submitted information on the server.
- Store valid records in a relational database using JDBC.
- Display a list of saved students.
- Provide a student details page.
- Handle missing records and invalid inputs gracefully.
- Separate controllers, models, services, DAOs, and views.
Suggested Project Structure
StudentManagementApp/
├── src/main/java/
│ └── com/example/
│ ├── controller/
│ │ ├── StudentListServlet.java
│ │ └── StudentCreateServlet.java
│ ├── model/
│ │ └── Student.java
│ ├── service/
│ │ └── StudentService.java
│ └── dao/
│ └── StudentDAO.java
├── src/main/webapp/
│ ├── index.html
│ └── WEB-INF/
│ └── views/
│ ├── student-form.jsp
│ └── student-list.jsp
└── pom.xml
Development Steps
- Create a Maven web application.
- Configure the Servlet API dependency for the selected Tomcat version.
- Design the student model and database table.
- Implement DAO methods for creating and retrieving records.
- Create service methods for validation and business logic.
- Implement servlet controllers for GET and POST requests.
- Create JSP views for the form and student list.
- Test valid submissions, invalid inputs, and database errors.
- Deploy the application to Tomcat and verify its URLs.
20. Interview Questions and Answers
Q1. What is a dynamic web application?
Answer: A dynamic web application generates or changes content based on user requests, application logic, database data, or other runtime information.
Q2. What is the role of a servlet?
Answer: A servlet receives requests, processes input, coordinates application logic, and produces or forwards an HTTP response.
Q3. What is the difference between doGet() and doPost()?
Answer: doGet() handles GET requests and is generally used to retrieve information. doPost() handles POST requests and is commonly used to submit data for processing.
Q4. What is the purpose of HttpServletRequest?
Answer: It provides access to request parameters, headers, the request URI, session information, and other details of an incoming HTTP request.
Q5. What is the purpose of HttpServletResponse?
Answer: It allows a servlet to set response headers and status codes and write content returned to the client.
Q6. Why should business logic be separated from servlet code?
Answer: Separating business logic improves maintainability, reuse, readability, and testability.
Q7. What is the DAO pattern?
Answer: Data Access Object is a pattern that isolates persistence operations from controllers and business logic.
Q8. What is the difference between forwarding and redirecting?
Answer: Forwarding transfers processing to another server-side resource using the current request. Redirecting instructs the client to make a new request to another URL.
Q9. What is an HTTP session?
Answer: An HTTP session allows an application to associate data with a user's interaction across multiple requests.
Q10. Why is input validation necessary?
Answer: Validation helps ensure that incoming values meet expected formats and business rules, reducing errors and security risks.
Q11. What is MVC architecture?
Answer: MVC separates the Model, View, and Controller to organize data, presentation, and request processing.
Q12. How can SQL injection be prevented in a servlet application?
Answer: Use prepared statements with parameter binding, validate input, and avoid constructing SQL by concatenating untrusted values.
21. Practice Exercises
- Create a servlet that displays a dynamic welcome message.
- Build an HTML form and process it using
doPost().
- Validate required fields on the server.
- Create a model class to represent a student.
- Use JDBC to insert and retrieve student records.
- Implement a DAO class to separate database operations from servlet code.
- Forward requests from a servlet to a JSP view.
- Redirect the browser after a successful form submission.
- Use an HTTP session to maintain appropriate user-specific state.
- Build a small student management application using MVC principles.
- Test invalid inputs and simulate database failures.
- Review the application for SQL injection, XSS, CSRF, and authorization issues.
22. Quick Revision Checklist
- Dynamic applications generate content using runtime data and business logic.
- Servlets process HTTP requests and help generate responses.
HttpServlet supports HTTP-specific request handling.
doGet() handles GET requests and doPost() handles POST requests.
HttpServletRequest provides access to incoming request data.
HttpServletResponse controls the outgoing response.
- JDBC can connect a servlet application's data layer to a relational database.
- DAO classes separate database operations from controllers.
- Services organize business rules and workflows.
- JSP or another view technology can separate presentation from servlet logic.
- Forwarding and redirecting serve different request-navigation purposes.
- Sessions can maintain user-specific state across requests.
- Validate inputs, escape output, and use prepared statements.
- Keep servlets thread-safe and avoid shared mutable request data.
- Test the application and review server logs before deployment.
23. Official Documentation and Learning Resources
24. Conclusion
Building dynamic web applications using Servlets is an important part of Advanced Java development. Servlets provide the request-handling foundation for processing forms, validating input, coordinating business logic, accessing databases, managing sessions, and generating responses.
For larger applications, combining servlets with model classes, service classes, DAO components, and JSP views creates a cleaner architecture that is easier to maintain and test. By practicing these concepts and deploying projects on a compatible servlet container, you can develop a strong foundation for enterprise Java web application development.
To continue learning, explore the Advanced Java Training course, register for a course demo, or visit the JustAcademy homepage.