Servlets and JSP Basics
1. Introduction
Servlets and JavaServer Pages (JSP) are fundamental components of Java EE (Enterprise Edition) for building dynamic web applications. Servlets handle requests and responses, while JSP allows for embedding Java code in HTML pages.
2. What are Servlets?
Servlets are server-side Java programs that handle client requests and generate dynamic responses. They run on a servlet container (like Apache Tomcat) and are an integral part of Java web applications.
3. What are JSP?
JavaServer Pages (JSP) are text-based documents that execute as servlets. JSP allows developers to embed Java code directly into HTML, making it easier to create dynamic web pages.
4. Servlet Lifecycle
The lifecycle of a servlet is managed by the servlet container and consists of the following stages:
- Loading and Instantiation
- Initialization (init method)
- Request Handling (service method)
- Destruction (destroy method)
public class MyServlet extends HttpServlet {
public void init() {
// Initialization code
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Handle GET request
}
public void destroy() {
// Cleanup code
}
}
5. JSP Lifecycle
The lifecycle of a JSP page is similar to that of a servlet and involves:
- Translation into a Servlet
- Compilation
- Initialization (init method)
- Handling Requests (service method)
- Destruction (destroy method)
6. Example: Servlet and JSP
Here’s a simple example demonstrating a servlet and a JSP page:
Servlet Code
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("message", "Hello from Servlet!");
RequestDispatcher dispatcher = request.getRequestDispatcher("hello.jsp");
dispatcher.forward(request, response);
}
}
JSP Code (hello.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Hello JSP
${message}