Java Servlets Notes: Extended Edition
1. Introduction to Servlets
A Servlet is a Java class used to handle HTTP requests and generate responses in a web
application.
Runs on a Servlet container (like Apache Tomcat).
Replaces traditional CGI scripts.
2. Servlet Lifecycle
Handled by the Servlet Container:
1. Loading and Instantiation
2. Initialization (init() method)
3. Request Handling (service() method)
4. Destruction (destroy() method)
3. Basic Servlet Program
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("Hello, Servlet!");
4. Key Classes and Interfaces
HttpServlet, HttpServletRequest, HttpServletResponse,
ServletConfig & ServletContext, RequestDispatcher,
HttpSession, Cookie
5. Deployment Descriptor (web.xml)
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
6. Servlet Annotations
@WebServlet("/login")
public class LoginServlet extends HttpServlet { ... }
7. Handling Form Data
Use request.getParameter("name") to read form input
doPost() is preferred for sensitive data like passwords
8. Redirect vs Forward
Forward: server-side (no URL change), RequestDispatcher.forward()
Redirect: client-side (URL changes), response.sendRedirect()
9. Session Management
HttpSession session = request.getSession();
session.setAttribute("user", "Nishanth");
Cookie cookie = new Cookie("user", "Nishanth");
response.addCookie(cookie);
10. JDBC with Servlets
Connect to DB in doPost() or doGet() method
Insert / retrieve data using PreparedStatements
11. Exception Handling
Use try-catch for database and input operations
Send errors via response.sendError() or custom error pages
12. File Upload Handling (Advanced)
Use Apache Commons FileUpload or Servlet 3.0 multipart API
13. Filters and Listeners
@WebFilter("/dashboard")
public class AuthFilter implements Filter { ... }
Listeners: track session, context, etc. (HttpSessionListener)
14. Best Practices
Avoid DB logic directly in Servlet --> use DAO pattern
Follow MVC (Model-View-Controller)
Use JSP for view layer
15. ServletContext vs ServletConfig
ServletContext:
- One per web application
- Used to share data between servlets
- Defined at application level
ServletConfig:
- One per servlet
- Used to pass init parameters to servlet
- Defined in web.xml
16. RequestDispatcher in Detail
Used to forward a request or include response from another resource (like another servlet or JSP).
Forward example:
RequestDispatcher rd = request.getRequestDispatcher("/next");
rd.forward(request, response);
Include example:
rd.include(request, response);
17. Servlet Filters
Filters can intercept requests and responses.
Used for logging, authentication, compression, etc.
@WebFilter("/admin")
public class AuthFilter implements Filter {
public void doFilter(...) { ... }
18. Servlet Listeners
Listeners react to events in servlet context, session, or request lifecycle.
Types:
- ServletContextListener
- HttpSessionListener
- ServletRequestListener
19. Cookie Handling in Depth
Creating a cookie:
Cookie c = new Cookie("username", "nishanth");
c.setMaxAge(3600);
response.addCookie(c);
Reading cookies:
Cookie[] cookies = request.getCookies();
20. Error Handling in Web Applications
In web.xml:
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
You can also handle exceptions using try-catch in servlets.
21. Multipart/Form-Data File Upload
@MultipartConfig is used in servlet to enable file uploads.
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(...) {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
22. MVC Architecture in Java Web Apps
- Model: Java Beans or POJOs that represent data
- View: JSP for presentation
- Controller: Servlets handle business logic and forward to views
23. DAO Pattern for DB Operations
Create a Data Access Object class to handle all database operations.
Benefits:
- Code reusability
- Separation of concerns
- Easier to maintain
Example: UserDAO with methods like addUser(), getUser(), deleteUser()
24. Building a Mini Project (Login System)
- RegistrationServlet: handles sign-up and inserts into DB
- LoginServlet: validates user and starts session
- DashboardServlet: shows user info
- LogoutServlet: invalidates session
Use JSP pages for input and output
Use JDBC for DB interaction