Web Development with Java: Servlets and JSP
Java Servlets and JavaServer Pages (JSP) are technologies used to create dynamic web applications. Servlets are Java programs that run on a server, while JSPs are HTML pages with embedded Java code. Together, they form the backbone of many Java-based web applications.
1. Java Servlets
A servlet is a Java class that handles HTTP requests and responses in a web application. It runs on a server and is capable of processing complex requests, interacting with databases, and generating dynamic content.
Lifecycle of a Servlet
- Loading and Instantiation: The servlet container loads the servlet class and creates an instance.
- Initialization: The
init
method is called once when the servlet instance is created. - Request Handling: The
service
method is called for each request. It dispatches requests to the appropriatedoGet
,doPost
,doPut
,doDelete
, etc., methods. - Destruction: The
destroy
method is called once when the servlet is being taken out of service.
Example: Simple Servlet
- Create a Servlet Class:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
- Configure the Servlet in
web.xml
:
<web-app>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
- Deploy and Access the Servlet:
Deploy the servlet in a web container like Apache Tomcat. Access it by navigating to http://localhost:8080/yourapp/hello
.
Servlet Request and Response
- HttpServletRequest: Provides methods to get information about the request, such as parameters, headers, and attributes.
- HttpServletResponse: Provides methods to control the response, such as setting headers, status codes, and writing output.
Example: Handling Form Data
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FormHandlerServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Form Data</h1>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Email: " + email + "</p>");
out.println("</body></html>");
}
}
2. JavaServer Pages (JSP)
JSP is a technology that allows you to create dynamically generated web pages based on HTML, XML, or other document types. JSPs enable the embedding of Java code directly into the HTML.
JSP Lifecycle
- Translation: The JSP file is translated into a servlet by the JSP engine.
- Compilation: The generated servlet is compiled into bytecode.
- Loading and Instantiation: The servlet class is loaded and instantiated.
- Initialization: The
jspInit
method is called once when the servlet instance is created. - Request Handling: The
service
method is called for each request, which in turn calls the_jspService
method. - Destruction: The
jspDestroy
method is called once when the servlet is being taken out of service.
Example: Simple JSP
- Create a JSP File:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Hello JSP</title>
</head>
<body>
<h1>Hello, JSP!</h1>
<p>Current Time: <%= new java.util.Date() %></p>
</body>
</html>
- Deploy and Access the JSP:
Deploy the JSP in a web container like Apache Tomcat. Access it by navigating to http://localhost:8080/yourapp/hello.jsp
.
JSP Scriptlets, Expressions, and Declarations
- Scriptlets: Embeds Java code within
<% ... %>
.
<% String message = "Hello, JSP!"; %>
<p><%= message %></p>
- Expressions: Outputs the result of a Java expression within
<%= ... %>
.
<p>Current Time: <%= new java.util.Date() %></p>
- Declarations: Declares Java variables and methods within
<%! ... %>
.
<%!
private int counter = 0;
private String getMessage() {
return "Hello, JSP!";
}
%>
<p><%= getMessage() %></p>
Using JSP with Servlets
JSPs can be used to render views while servlets handle the business logic. This separation of concerns follows the MVC (Model-View-Controller) design pattern.
Example: Servlet Forwarding to JSP
- Servlet Code:
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
request.setAttribute("name", name);
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
}
}
- JSP Code (
welcome.jsp
):
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <%= request.getAttribute("name") %>!</h1>
</body>
</html>
Using JSP Standard Tag Library (JSTL)
JSTL provides tags to perform common tasks like iteration, conditionals, and formatting. It promotes a cleaner separation of Java code from HTML.
- Include JSTL Library:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
- JSP with JSTL Tags:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>JSTL Example</title>
</head>
<body>
<h1>JSTL Example</h1>
<c:forEach var="i" begin="1" end="5">
<p>Number: ${i}</p>
</c:forEach>
</body>
</html>
Summary
Servlets and JSP are core technologies for building dynamic web applications in Java.
- Servlets: Java classes that handle HTTP requests and generate responses. They are powerful for processing complex business logic.
- JSP: HTML pages with embedded Java code, used primarily for rendering dynamic content and views. They simplify the creation of dynamic web pages by allowing Java code to be mixed with HTML.
Together, servlets and JSP provide a robust platform for developing web applications using the Java programming language.