JDBC, servlets and JSP based applications notes — Unit 5
Free unit-wise study notes on jdbc, servlets and jsp based applications for Java Programming, Semester 5 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
JDBC, servlets and JSP based applications
Notebook — 20 pages
Page 1
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
1. JDBC Introduction
JDBC (Java Database Connectivity) is an API that allows Java applications to interact with relational databases (like MySQL, Oracle).
⇒1.1 The Architecture
JDBC is composed of two layers:
JDBC API: The interfaces (`Connection`, `Statement`, `ResultSet`) that developers code against. Provided in the `java.sql` package.
JDBC Driver API: The bridge between the standard Java API and the proprietary database protocol. Each database vendor (Oracle, MySQL) provides their own `.jar` driver file.
Page 2
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
2. Connecting to a Database
⇒2.1 The 4 Standard Steps
// 1. Load the Driver (Optional in modern JDBC)
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Establish Connection
String url = "jdbc:mysql://localhost:3306/mydb";
Connection con = DriverManager.getConnection(url, "user", "password");
// 3. Create Statement
Statement stmt = con.createStatement();
// 4. Execute Query
ResultSet rs = stmt.executeQuery("SELECT * FROM Users");
Page 3
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
3. Statement vs PreparedStatement
A standard `Statement` concatenates raw strings into SQL queries. This is highly vulnerable to SQL Injection.
⇒3.1 PreparedStatement
Precompiled by the database. It uses placeholders `?` and safely escapes all inputs. Always use PreparedStatement for variables.
String query = "UPDATE users SET email = ? WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "new@email.com");
pstmt.setInt(2, 45);
int rowsAffected = pstmt.executeUpdate();
Page 4
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
4. ResultSet and Execution Methods
⇒4.1 Execution Methods
`executeQuery()`: Used for SELECT statements. Returns a `ResultSet`.
`executeUpdate()`: Used for INSERT, UPDATE, DELETE. Returns an `int` (rows affected).
⇒4.2 Processing the ResultSet
The ResultSet acts like a cursor pointing before the first row of data.
while(rs.next()) { // Moves cursor forward, returns false if no more rows
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " - " + name);
}
Page 5
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
5. Transaction Management
By default, JDBC operates in Auto-Commit mode (every single query is committed immediately). For complex operations (like a bank transfer involving two accounts), this must be disabled.
⇒5.1 Manual Commits
con.setAutoCommit(false); // Start transaction
try {
// ... Execute Query 1 (Deduct from A)
// ... Execute Query 2 (Add to B)
con.commit(); // If both succeed, save permanently
} catch (SQLException e) {
con.rollback(); // If anything fails, revert entirely
}
Page 6
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
6. Introduction to Servlets
A Servlet is a Java class that runs on a Web Server. It intercepts incoming HTTP requests from browsers, processes them (usually by hitting a database), and returns an HTTP response.
⇒6.1 Web Containers (Tomcat)
Servlets do not have a `main()` method. They are managed by a Web Container (like Apache Tomcat). The container handles the network socket connection, creates an HTTP Request object, and passes it to the Servlet.
Page 7
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
7. The Servlet Life Cycle
The container manages the servlet through three main methods.
`init()`: Called exactly once when the servlet is first loaded into memory. Used for heavy setup tasks (like opening DB connections).
`service()`: Called for every single incoming HTTP request. In `HttpServlet`, this automatically delegates to `doGet()` or `doPost()`.
`destroy()`: Called exactly once when the server is shutting down to release resources.
Crucially, there is only one instance of a given servlet class in memory. Multiple incoming user requests are handled concurrently by multiple threads calling the `service()` method on that single instance.
Page 8
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
8. HttpServlet and Request Handling
Almost all web servlets extend `HttpServlet`.
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Read form data
String user = request.getParameter("username");
// Send response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Welcome " + user + "</h1>");
}
}
Page 9
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
9. Session Tracking
Because HTTP is stateless, Servlets must manually track users across multiple requests.
⇒9.1 HttpSession
The container automatically generates a unique Session ID, sends it to the browser as a Cookie, and intercepts it on subsequent requests.
// Creates a new session, or retrieves the existing one
HttpSession session = request.getSession();
// Store data on the server tied to this user
session.setAttribute("userID", 105);
// Log out
session.invalidate();
Page 10
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
10. Request Dispatcher vs Redirect
When a Servlet finishes processing, it rarely outputs HTML directly. It usually passes control to a JSP file to render the UI.
⇒10.1 `RequestDispatcher.forward()`
Happens entirely on the server. The URL in the browser does not change. The request and response objects are passed directly to the next file.
⇒10.2 `response.sendRedirect()`
The server sends an HTTP 302 code to the browser. The browser makes a completely brand new HTTP GET request to the new URL. The URL bar changes. Original request data is lost.
Page 11
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
11. JavaServer Pages (JSP)
Writing HTML using `out.println("<h1>")` inside a Servlet is a nightmare to maintain. JSP solves this by flipping the paradigm: it allows you to write standard HTML files, and embed snippets of Java code inside them.
⇒11.1 How JSP Works
JSP is an abstraction. The first time a browser requests `index.jsp`, Tomcat intercepts it, reads the file, completely translates it into a standard Java Servlet (`index_jsp.java`), compiles it, and runs it. Every subsequent request hits the compiled Servlet.
Page 12
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
12. JSP Scripting Elements
These are tags used to insert Java into the HTML.
Scriptlet `<% code %>`: Inserts raw Java code into the `service()` method of the generated servlet.
Expression `<%= data %>`: Evaluates the expression and outputs it to the HTML. (No semicolon at the end).
Declaration `<%! code %>`: Declares variables or methods outside the `service()` method (as instance variables of the generated servlet).
<p>The time is: <%= new java.util.Date() %></p>
<%
for(int i=0; i<3; i++) {
%>
<p>Loop iteration!</p>
<% } %>
Page 13
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
13. JSP Directives and Implicit Objects
⇒13.1 Directives `<%@ ... %>`
Used to give instructions to the container during the translation phase.
While Servlets are the foundation of Java Web, developers rarely write raw Servlets today. They use frameworks built on top of the Servlet API.
⇒16.1 Spring Boot
The industry standard. It provides an embedded Tomcat server and an abstraction layer called Spring MVC.
Uses annotations (`@RestController`, `@GetMapping`) instead of extending `HttpServlet`.
Returns JSON automatically instead of manual `PrintWriter` manipulation.
Uses Spring Data JPA (Hibernate) instead of raw JDBC queries.
Page 17
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
17. Enterprise JavaBeans (Legacy)
EJB is a legacy server-side software architecture that encapsulates business logic. While mostly replaced by Spring today, it remains in university syllabi.
⇒17.1 Types of Beans
Stateless Session Beans: Do not maintain conversational state with the client. (E.g., A math calculator bean).
Stateful Session Beans: Maintain state across multiple requests for a single client. (E.g., A shopping cart bean).
Opening a new database connection via JDBC is extremely slow (network handshakes, authentication). If 1,000 users connect, opening 1,000 connections will crash the database.
⇒18.1 The Solution
A Connection Pool (like HikariCP) opens a fixed number of connections (e.g., 20) when the server starts. When a Servlet needs the DB, it 'borrows' a connection from the pool. When finished, it 'returns' it to the pool instead of closing it.
Page 19
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
19. Security in Java Web Applications
⇒19.1 Preventing SQL Injection
As discussed, ALWAYS use `PreparedStatement` instead of `Statement`.
⇒19.2 Preventing XSS
When displaying user input via JSP, always escape it. JSTL's `<c:out value="${user.comment}" />` automatically escapes HTML characters, preventing malicious JavaScript from executing.
⇒19.3 Filter API
A Servlet Filter sits in front of the Servlets. It intercepts every request and response. It is used for tasks like checking if a valid Session exists before allowing access to a secure URL.
Page 20
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 5 —
20. The Evolution of Java Web
The concepts learned in this unit map directly to modern architecture:
Raw JDBC evolved into ORMs (Hibernate) and Spring Data JPA.
Raw Servlets evolved into Spring MVC Controllers (`@RestController`).