[Go to site: main page, start]

0% found this document useful (0 votes)
3 views13 pages

Java Servlets Notes

Uploaded by

johjooh0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Java Servlets Notes

Uploaded by

johjooh0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Servlets

1. What is a Servlet?
A Servlet is a Java program that runs on a web server (inside a Servlet container such as Apache Tomcat) and
handles HTTP requests from clients (usually web browsers). It is a server-side technology used to create dynamic
web pages and web applications.

Key characteristics of Servlets:


• Platform-independent (written in Java, runs on any OS)
• More efficient than CGI scripts (no new process per request)
• Part of the Java EE (Enterprise Edition) specification
• Runs inside a Servlet container / web container (e.g., Tomcat)
• Can handle HTTP, HTTPS, and other protocols

1.1 Servlet vs. JSP vs. CGI


Feature Servlet JSP CGI
Language Java Java (embedded) Any (Perl, Python...)
Performance High (single instance) High (compiled to Low (new
Servlet) process/request)
Reusability High Medium Low
Separation of concerns Low (Java handles High (HTML + Java) Low
HTML)
Use Case Business logic, Presentation layer Legacy scripts
controllers

2. Servlet Architecture & Lifecycle


Servlets follow a well-defined lifecycle managed entirely by the Servlet container:

2.1 Lifecycle Stages


1. Loading & Instantiation — The container loads the Servlet class and creates one instance.
2. init() — Called once when the Servlet is first loaded. Used for one-time initialization (DB connections,
config loading).
3. service() — Called for every client request. Dispatches to doGet(), doPost(), doPut(), doDelete(), etc.
4. destroy() — Called once when the Servlet is removed or server shuts down. Used for cleanup.

2.2 HTTP Methods Handled by Servlets


Method Override in Servlet Purpose
GET doGet() Retrieve data / load page
POST doPost() Submit form data / create resource
PUT doPut() Update an existing resource
DELETE doDelete() Delete a resource
HEAD doHead() Same as GET but no body
OPTIONS doOptions() List supported methods
3. Prerequisites & Tools Required
3.1 Software to Install
Tool Version (Recommended) Download URL
Java JDK JDK 11 or 17 (LTS) [Link]
Eclipse IDE Eclipse IDE for Enterprise [Link]
Java
Apache Tomcat Tomcat 10.x or 9.x [Link]
Servlet API JAR Included with Tomcat Inside Tomcat /lib folder

Note: Eclipse IDE for Enterprise Java (formerly Eclipse IDE for Java EE Developers) comes
with built-in support for Dynamic Web Projects, making Servlet development much easier.

3.2 Environment Setup


Step 1 — Install JDK
5. Download JDK 11 or 17 from [Link]
6. Run the installer and follow on-screen instructions
7. Set JAVA_HOME environment variable to your JDK folder (e.g., C:\Program Files\Eclipse
Adoptium\jdk-17)
8. Add %JAVA_HOME%\bin to your system PATH
9. Verify: open Command Prompt and run: java -version
Step 2 — Install Eclipse IDE
10. Download Eclipse IDE for Enterprise Java and Web Developers
11. Extract the zip file to a folder (e.g., C:\eclipse)
12. Launch [Link] and select a workspace folder when prompted

Step 3 — Install Apache Tomcat


13. Download Apache Tomcat 10.x (zip/[Link]) from [Link]
14. Extract to a folder (e.g., C:\tomcat10)
15. No additional installation needed — Tomcat runs from this folder

4. Creating Your First Servlet in Eclipse


4.1 Step 1 — Create a Dynamic Web Project
16. Open Eclipse IDE
17. Go to File > New > Project...
18. Expand Web folder and select Dynamic Web Project, then click Next
19. Enter a Project Name (e.g., "MyServletApp")
20. In Target Runtime, click New Runtime...
21. Select Apache Tomcat v10.0 (or your version), click Next
22. Browse to your Tomcat installation folder and click Finish
23. Back in the project wizard, make sure Dynamic Web Module version is 5.0 (for Tomcat 10) or 4.0 (for
Tomcat 9)
24. Click Next twice, then check Generate [Link] deployment descriptor
25. Click Finish

Tip: You should now see your project in the Project Explorer on the left side of Eclipse, with
folders: Java Resources/src, WebContent (or src/main/webapp), and WEB-INF.

4.2 Step 2 — Create a Servlet Class


26. In Project Explorer, right-click on your project > New > Servlet
27. Enter the Java package name (e.g., [Link])
28. Enter the Class name (e.g., HelloServlet)
29. Click Next — you can review the URL mapping (default: /HelloServlet)
30. Click Next again — select which methods to generate (doGet, doPost)
31. Click Finish

Eclipse will generate a skeleton class like this:


package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// Called for HTTP GET requests


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Set the response content type


[Link]("text/html");

// Get a PrintWriter to write HTML response


PrintWriter out = [Link]();

[Link]("<html>");
[Link]("<head><title>Hello Servlet</title></head>");
[Link]("<body>");
[Link]("<h1>Hello from Java Servlet!</h1>");
[Link]("<p>This is my first servlet.</p>");
[Link]("</body></html>");
}

// Called for HTTP POST requests


protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response); // Delegate to doGet
}
}

Important: For Tomcat 10+, use '[Link].*' imports (not '[Link].*'). Tomcat 9 and
below use '[Link].*'. This is a common source of errors.

4.3 Step 3 — Understanding @WebServlet Annotation


The @WebServlet annotation (available since Servlet 3.0) registers the servlet with the container without needing
[Link] entries:
// Basic URL mapping
@WebServlet("/HelloServlet")

// Multiple URL patterns


@WebServlet(urlPatterns = {"/hello", "/greet"})

// Full annotation with name and load-on-startup


@WebServlet(
name = "HelloServlet",
urlPatterns = {"/hello"},
loadOnStartup = 1 // Load this servlet when server starts
)

4.4 Step 4 — Configuring [Link] (Alternative to Annotation)


If you prefer XML configuration (older style, or need more control), use WEB-INF/[Link]:

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="[Link]
version="5.0">

<!-- Declare the Servlet -->


<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Map URL to Servlet -->


<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

4.5 Step 5 — Run the Servlet on Tomcat


32. In Project Explorer, right-click your project
33. Select Run As > Run on Server
34. In the dialog, select Tomcat v10.0 Server (or your version)
35. Click Next, confirm your project is listed under Configured, then click Finish
36. Eclipse opens the built-in browser. Navigate to:

[Link]
37. You should see: Hello from Java Servlet!

Troubleshooting: If port 8080 is busy, double-click the server in the Servers view and change
the HTTP port under Ports section.

5. Working with Request & Response


5.1 HttpServletRequest — Reading Input
The HttpServletRequest object provides access to everything sent by the client:

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// ── Reading form parameters ──


String username = [Link]("username");
String password = [Link]("password");

// ── Multiple values (e.g., checkboxes) ──


String[] hobbies = [Link]("hobby");

// ── Reading request headers ──


String userAgent = [Link]("User-Agent");
String contentType = [Link]();

// ── Reading attributes (set by other servlets/filters) ──


Object attr = [Link]("myAttribute");

// ── Session and context ──


HttpSession session = [Link]();
String contextPath = [Link]();
String requestURI = [Link]();
String method = [Link](); // GET, POST, etc.

// ── Remote client info ──


String clientIP = [Link]();
}

5.2 HttpServletResponse — Sending Output


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// ── Set content type (MUST be set before getWriter) ──


[Link]("text/html;charset=UTF-8");

// ── Set HTTP status code ──


[Link](HttpServletResponse.SC_OK); // 200
// [Link](HttpServletResponse.SC_NOT_FOUND); // 404

// ── Add response headers ──


[Link]("Cache-Control", "no-cache");
[Link](new Cookie("user", "john"));

// ── Write HTML response ──


PrintWriter out = [Link]();
[Link]("<h1>Response Sent!</h1>");

// ── Redirect to another URL ──


// [Link]("[Link]

// ── Send error response ──


// [Link](404, "Resource not found");
}

6. Session Management
6.1 What is a Session?
HTTP is a stateless protocol — each request is independent. Sessions allow the server to remember data across
multiple requests from the same user (e.g., login state, shopping cart).

6.2 Using HttpSession


// ── Creating / retrieving a session ──
HttpSession session = [Link](); // create if not exists
HttpSession session = [Link](false); // return null if not exists

// ── Storing data in session ──


[Link]("loggedInUser", username);
[Link]("cartItems", cartList);

// ── Reading data from session ──


String user = (String) [Link]("loggedInUser");

// ── Session info ──
String sessionId = [Link]();
long creationTime = [Link]();

// ── Set session timeout (seconds) ──


[Link](30 * 60); // 30 minutes

// ── Invalidate (logout) ──
[Link]();

6.3 Session Tracking Methods


Method How it Works Pros / Cons
Cookies Session ID stored in browser cookie Easy; blocked if cookies disabled
URL Rewriting Session ID appended to every URL Works without cookies; ugly URLs
Hidden Fields Session ID in hidden form inputs Only works for forms
SSL Sessions Server uses SSL session ID Secure; complex to implement

7. Servlet Filters
Filters intercept requests and responses before they reach a Servlet. Common uses: authentication, logging,
compression, encoding.

import [Link].*;
import [Link];
import [Link];

@WebFilter("/*") // Apply to all URLs


public class LoggingFilter implements Filter {

@Override
public void init(FilterConfig config) throws ServletException {
[Link]("LoggingFilter initialized");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {

// ── Code here runs BEFORE the Servlet ──


[Link]("Request received: " +
((HttpServletRequest) request).getRequestURI());

// ── Pass request to next filter or servlet ──


[Link](request, response);

// ── Code here runs AFTER the Servlet ──


[Link]("Response sent.");
}

@Override
public void destroy() {
[Link]("LoggingFilter destroyed");
}
}

8. RequestDispatcher — Forwarding & Including


8.1 Forward
Forwards the request to another servlet or JSP. The browser URL does not change.
RequestDispatcher rd = [Link]("/[Link]");
[Link](request, response);

8.2 Include
Includes the output of another servlet/JSP inside the current response.
RequestDispatcher rd = [Link]("/[Link]");
[Link](request, response);
// Continue writing to response after include...

8.3 Redirect vs Forward


Aspect sendRedirect() [Link]()
Browser URL Changes to new URL Stays the same
Round trips 2 (new request from browser) 1 (server-side only)
Data sharing Cannot share request attributes Can share request attributes
Use case After login, after form submit MVC pattern, error pages

9. Practical Example — Login Servlet


A complete login form example demonstrating doGet (show form) and doPost (process form):

9.1 HTML Login Form ([Link] in WebContent)


<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="post">
<label>Username: <input type="text" name="username"></label><br><br>
<label>Password: <input type="password" name="password"></label><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

9.2 [Link]
package [Link];

import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

// Show the login form (GET request)


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

[Link]("[Link]");
}

// Process login form submission (POST request)


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

String username = [Link]("username");


String password = [Link]("password");

[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();

// Simple validation (use database check in real apps)


if ("admin".equals(username) && "password123".equals(password)) {

// Create session and store user


HttpSession session = [Link]();
[Link]("user", username);
[Link](30 * 60); // 30 min

// Forward to dashboard
RequestDispatcher rd =
[Link]("/[Link]");
[Link](request, response);

} else {
[Link]("<h3 style='color:red'>Invalid credentials!</h3>");
[Link]("<a href='[Link]'>Try Again</a>");
}
}
}

10. Common Errors & Troubleshooting


Error Likely Cause Solution
404 Not Found Wrong URL or servlet not Check @WebServlet URL pattern matches your
mapped URL
ClassNotFoundException Missing Servlet API JAR Add [Link] to build path or use Maven
javax vs jakarta error Wrong import for Tomcat Tomcat 10+ needs jakarta.*, Tomcat 9 needs
version javax.*
500 Internal Server Error Exception in servlet code Check Eclipse Console for stack trace
Port 8080 in use Another process using the port Change port in server config or stop other app
Changes not reflected Old class files cached Clean project: Project > Clean, restart Tomcat
NullPointerException on Parameter name mismatch Check HTML form field name matches
getParameter getParameter() arg

11. Servlet Project Structure in Eclipse


MyServletApp/
├── Java Resources/
│ └── src/
│ └── com/myapp/servlets/
│ ├── [Link]
│ └── [Link]
├── WebContent/ (or src/main/webapp for Maven projects)
│ ├── WEB-INF/
│ │ ├── [Link] <- Deployment descriptor
│ │ └── lib/ <- External JARs (if not using Maven)
│ ├── [Link]
│ ├── [Link]
│ └── [Link]
└── build/
└── classes/ <- Compiled .class files (auto-generated)

12. Quick Reference — Key Classes & Methods


Class / Interface Package Key Purpose
HttpServlet [Link] Base class to extend for all HTTP
servlets
HttpServletRequest [Link] Represents the client HTTP request
HttpServletResponse [Link] Represents the server HTTP response
HttpSession [Link] Manages user session across requests
RequestDispatcher [Link] Forwards/includes requests to other
resources
ServletConfig [Link] Servlet initialization parameters
ServletContext [Link] Application-wide shared data and
resources
Filter [Link] Interface to implement for
request/response filtering
Cookie [Link] HTTP cookie creation and retrieval

Summary
Servlets are the foundation of Java web development. Key takeaways:
• Servlets extend HttpServlet and override doGet() / doPost()
• Use @WebServlet annotation for URL mapping (Servlet 3.0+)
• HttpServletRequest reads client data; HttpServletResponse sends replies
• Sessions keep state across requests (stateless HTTP)
• Filters intercept requests for cross-cutting concerns (logging, auth)
• RequestDispatcher enables server-side forwarding in MVC patterns
• Always use [Link].* for Tomcat 10+, [Link].* for Tomcat 9

Good luck with your Java Servlet development!

You might also like