Advanced Java ProgrammingUnit 69 min read
Servlets & JSP: Architecture, Lifecycle, and Web Development
Unit 6 of Advanced Java Programming covers Servlets (architecture, lifecycle, request handling) and JSP (syntax, implicit objects, scopes, and database integration) with practical examples, comparisons, and exam-focused insights.
TAKEAWAYS:
- Servlets are server-side Java programs that extend
HttpServletand handle HTTP requests/responses via lifecycle methods (init(),service(),destroy()). - JSP (JavaServer Pages) embeds Java in HTML/XML for dynamic web content, using implicit objects (
request,response,session, etc.) and scopes (page,request,session,application). - Key difference: Servlets are Java-centric (compiled to
.class), while JSPs are HTML-centric (converted to servlets at runtime). - Database integration uses JDBC in both Servlets/JSP, with connection pooling (e.g.,
DataSource) for efficiency. - Cookies/sessions manage state: cookies (client-side) for persistence, sessions (server-side) for user tracking.
- Exam focus: Lifecycle diagrams, code snippets (form handling, JDBC queries), and comparisons (Servlet vs. JSP vs. HTML).
1. Servlets: Core Concepts
1.1 Definition and Architecture
Servlets are server-side Java programs that extend javax.servlet.http.HttpServlet to process HTTP requests and generate dynamic responses. They run within a servlet container (e.g., Tomcat, Jetty) and follow the MVC pattern (Model-View-Controller):
flowchart TD
A[Client] -->|HTTP Request| B[Servlet Container]
B --> C[Servlet]
C -->|Process| D[Database/JDBC]
C -->|Generate| E[HTML/JSON Response]
E -->|HTTP Response| A1.2 Servlet Lifecycle
A servlet’s lifecycle is managed by the container via three methods:
init(): Called once when the servlet is loaded (initialization).service(): Handles every request (delegates todoGet(),doPost(), etc.).destroy(): Called once before unloading (cleanup).
Example Trace:
- User requests
/login→ Container loadsLoginServlet→init()runs. - User submits form →
service()→doPost()processes data. - Server shuts down →
destroy()releases resources.
1.3 Writing Servlets
Three Ways:
- Extending
HttpServlet(traditional):public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.getWriter().write("Hello, World!"); } } - Implementing
Servletinterface (low-level, rare). - Annotations (modern, e.g.,
@WebServlet):@WebServlet("/hello") public class HelloServlet extends HttpServlet { // ... }
1.4 Handling HTTP Requests/Responses
- Request Object (
HttpServletRequest):- Methods:
getParameter(),getHeader(),getSession(). - Example: Retrieve form data:
String username = req.getParameter("user");
- Methods:
- Response Object (
HttpServletResponse):- Methods:
getWriter(),sendRedirect(),setHeader(). - Example: Redirect after login:
res.sendRedirect("dashboard.jsp");
- Methods:
1.5 Advantages/Disadvantages
| Pros | Cons |
|---|---|
| Platform-independent (Java) | Steep learning curve |
| High performance (compiled) | Verbose XML config (pre-annotations) |
| Reusable business logic | Thread safety requires care |
| Integrates with JDBC, JNDI | Debugging harder than JSP |
2. JSP: Dynamic Web Pages
2.1 Definition and Syntax
JSP (JavaServer Pages) embeds Java in HTML/XML to generate dynamic content. Key features:
- Scriptlets: Java code blocks (
<% ... %>). - Expressions: Output values (
<%= expression %>). - Declarations: Variable/method definitions (
<%! ... %>). - Directives: Page/configuration (
<%@ page ... %>).
Example:
<%@ page contentType="text/html" %>
<html>
<head><title>JSP Example</title></head>
<body>
<h1>Hello, <%= request.getParameter("name") %></h1>
</body>
</html>
2.2 JSP vs. Servlet
| Feature | Servlet | JSP |
|---|---|---|
| Purpose | Business logic | Presentation logic |
| Extension | .java → .class |
.jsp → converted to servlet |
| Syntax | Pure Java | HTML + Java snippets |
| Use Case | Complex processing (e.g., DB ops) | UI-heavy pages (e.g., forms) |
| Performance | Faster (pre-compiled) | Slower (converted at runtime) |
2.3 Implicit Objects
JSP provides 9 implicit objects (predefined variables):
| Object | Scope | Purpose |
|---|---|---|
request |
Request | HTTP request data |
response |
Request | HTTP response generation |
session |
Session | User-specific data |
application |
Application | Global app data |
out |
Page | Output stream |
pageContext |
Page | Access other scopes/objects |
config |
Page | ServletConfig equivalent |
page |
Page | Current JSP page instance |
exception |
Page | Error handling (in error pages) |
Example: Access session data:
<% session.setAttribute("user", "Alice"); %>
Welcome, <%= session.getAttribute("user") %>
2.4 JSP Scopes
Objects in JSP have 4 scopes (lifetime):
page: Current JSP only.request: Current request (forwarded includes).session: User’s session (browser tab).application: Entire web app (server-wide).
Example: Set/get in different scopes:
<%-- Page scope --%>
<%@ page import="java.util.*" %>
<% Random rand = new Random(); %> // Only in this JSP
<%-- Request scope --%>
<% request.setAttribute("message", "Hello"); %>
<%-- Session scope --%>
<% session.setAttribute("user", "Bob"); %>
<%-- Application scope --%>
<% getServletContext().setAttribute("count", 0); %>
3. Servlets + JSP: Practical Integration
3.1 Form Handling Example
HTML Form (index.html):
<form action="process.jsp" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
JSP Processor (process.jsp):
<%@ page import="java.io.*" %>
<html>
<body>
<h2>Full Name: <%= request.getParameter("fname") + " " +
request.getParameter("lname") %></h2>
</body>
</html>
3.2 JDBC with JSP
JSP to Query TEACHER Table:
<%@ page import="java.sql.*" %>
<%!
Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "user", "pass");
}
%>
<%--
a. Select all teachers
--%>
<% Connection conn = getConnection(); %>
<table border="1">
<tr><th>ID</th><th>Name</th></tr>
<% ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEACHER"); %>
<% while (rs.next()) { %>
<tr><td><%= rs.getInt("ID") %></td><td><%= rs.getString("Name") %></td></tr>
<% } %>
</table>
<%--
b. Insert a teacher
--%>
<% conn.createStatement().executeUpdate("INSERT INTO TEACHER VALUES (8, 'Ramesh')"); %>
Record inserted!
3.3 Cookies and Sessions
Setting a Cookie:
<% Cookie userCookie = new Cookie("username", "Alice"); %>
<% response.addCookie(userCookie); %>
Reading a Cookie:
<% Cookie[] cookies = request.getCookies(); %>
<% for (Cookie c : cookies) { %>
<% if ("username".equals(c.getName())) { %>
Welcome, <%= c.getValue() %>
<% } %>
<% } %>
Session Tracking:
<% session.setAttribute("user", "Alice"); %>
Logged in as: <%= session.getAttribute("user") %>
4. Exam Tip: High-Scoring Strategies
Lifecycle Diagrams:
- Draw the servlet lifecycle with
init()→service()→destroy()arrows. - Label thread safety notes (e.g.,
service()handles multiple requests concurrently).
- Draw the servlet lifecycle with
Code Snippets:
- Must-know examples:
- Servlet form handling (
doPost()). - JSP implicit objects (
request.getParameter()). - JDBC queries in JSP (
<%! %>for connection pooling).
- Servlet form handling (
- Must-know examples:
Comparisons:
- Servlet vs. JSP: Use a table (as above) + 1–2 sentences per row.
- Scopes: Draw a Venn diagram showing
page(innermost) toapplication(outermost).
Database Questions:
- For JDBC in JSP, show:
- Connection setup (
<%! %>). - Query execution (
executeQuery()/executeUpdate()). - Result handling (
ResultSetloop).
- Connection setup (
- For JDBC in JSP, show:
Common Pitfalls:
- Thread safety: Servlets are not thread-safe by default (use
synchronizedor stateless design). - JSP conversion: JSPs are translated to servlets at runtime (hidden complexity).
- Session timeout: Default is 30 minutes (configure in
web.xml).
- Thread safety: Servlets are not thread-safe by default (use
Based on the TU BSc CSIT syllabus for Advanced Java Programming (CSC409), unit 6.
Discussion
Loading…