Unit 6 Serverlets and JSP
Unit 6 Serverlets and JSP
In Java, web applications are commonly built using technologies such as Servlets, JavaServer Pages (JSP),
and JavaServer Faces (JSF). Here's a brief explanation of each:
Servlets:
Servlet is a Server-Side technology which is used to handle the client request, process the
request and generate the dynamic response.
Servlets are Java classes that handle HTTP requests and generate HTTP responses. They run on
the server side and are part of the Java EE (Enterprise Edition) platform. Servlets can process
form submissions, retrieve data from a database, and generate dynamic content to be sent back
to the client.
Server are two types:
Web Server and
Application Server
JavaServer Pages (JSP):
JSP is a technology that allows you to embed Java code within HTML pages. It simplifies the
process of creating dynamic web pages by enabling developers to write Java code directly in the
web page, which is then compiled into a servlet by the server. This makes it easier to separate the
presentation layer (HTML) from the business logic (Java code).
JavaServer Faces (JSF):
JSF is a framework for building user interfaces for web applications in Java. It provides a
component-based model for creating reusable UI components, along with a set of standard UI
components that can be easily integrated into web pages. JSF also includes features for managing
user input, handling events, and validating user input.
1. HTTP Methods:
1.1. GET:
● The GET method requests data from a specified resource.
● It is typically used for retrieving information from the server.
● In Java, you can handle GET requests in servlets or controller methods using frameworks like
Spring MVC or JAX-RS.
1.2. POST:
● The POST method submits data to be processed to a specified resource.
● It is commonly used for creating or updating resources on the server.
● In Java, you can handle POST requests similar to GET requests, typically in servlets or controller
methods.
1.3. PUT:
● The PUT method updates a resource or creates a new resource if it doesn't exist.
● It is commonly used for updating existing resources with new data.
● In Java, you can handle PUT requests similarly to POST requests, typically in servlets or controller
methods.
1.4. DELETE:
● The DELETE method deletes the specified resource.
● It is used for deleting resources on the server.
● In Java, you can handle DELETE requests similarly to GET and POST requests.
2. HTTP Responses:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>Hello, world!</body></html>");
The Servlet container running a Servlet’s init () method, which initializes Servlet, once in the Servlet life
cycle, after loading the Servlet and create a Servlet object. The init method definition looks like this:
public void init(ServletConfig config) throws ServletException {
// Initialization code...
}
When instantiating the servlet container passes an argument to the init() method a ServletConfig object
for loading specific configuration settings to the servlet.
If an error occurs upon calling the init () method, it throws an exception of type and ServletException
servlet is not initialized.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service.
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet,
doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the
signature of these two methods.
The Servlet container running a servlet’s destroy () method once in a lifetime to close the Servlet. The
destroy method definition looks like this:
public void destroy() {
// Finalization code...
}
The destroy ( ) method waits until all threads started by the service () method before terminating the
execution of the servlet.
Note– The init() and destroy() method only once called during its servlet life cycle.
Architecture Diagram of Servlet Life Cycle:
The servlet is loaded at server startup or when the first request. The servlet is instantiated by the
server. The init ( ) method is invoked by the container. In the first application, the container creates
specific Request and Response objects to the query.
The service () method is called for each request in a new thread. The Request and Response objects are
passed as parameters. Through the Request object, the service () method will be able to analyze
information from the client With the Response object, the service () method will provide a response to
the client.
This method can be executed by multiple threads; there should be exclusion for the use of certain
resources processes.
The destroy () method is called when unloading the servlet, that is to say when it is no longer required
by the server. The servlet is then reported to the garbage collector.
Servlets are created using the javax.servlet and javax.servlet.http packages. These packages are a standard
part of Java’s enterprise edition and an expanded version of the Java class library that supports large-scale
development projects.
Package javax.servlet.*
It contains a number of classes and interfaces. It describes and defines the contracts between a servlet class
and the runtime environment.
Classes in javax.servlet.* package
● AsyncEvent: The event that gets fired when the asynchronous operation initiated on a
ServletRequest has completed, timed out, or produced an error.
● GenericServlet: It is used to define a generic, protocol-independent servlet.
● HttpConstraintElement: It is a java class representation of an HttpConstraint annotation
value.
● HttpMethodConstraintElement: It is a java class representation of an HttpMethodConstraint
annotation value.
● MultipartConfigElement: It is a java class representation of a MultipartConfig annotation
value.
● ServletContextAttributeEvent: It is an event class notification about changes to the attribute
of the ServletContext of a web application.
● ServletContextEvent: It provides an event class for notifications about changes to the servlet
context of a web application.
● ServletInputStream: It provides an input stream for reading binary data from a client request,
including an efficient readLine method for reading data one line at a time.
● ServletOutputStream: It provides an output stream for sending binary data to the client.
● ServletRequestAtrributeEvent: An event class for notifications of changes to the attributes of
the servlet request in an application.
● ServletRequestEvent: This event indicates lifecycle events for a ServletRequest.
● ServletRequestWrapper: It provides a convenient implementation of the ServletRequest
interface that can be subclassed by developers wishing to adapt the request to a Servlet.
● ServletResponseWrapper: It helps provides a convenient implementation of the
ServletResponse interface that can be subclassed by developers wishing to adapt the
response from a Servlet.
● ServletSecurityElement: It is a java class representation of a ServletSecurity annotation value.
● AsyncContext: The class representing the execution context for an asynchronous operation
that was initiated on a ServeltRequest.
● AsyncListener: It is a Listener that will be notified in the event that an asynchronous
operation initiated on a ServletRequest to which the listener had been added has completed,
timed out, or resulted in an error.
● Filter: It performs filtering tasks on either the request to a resource, or on the response from
a resource, or both.
● FilterChain: The servlet container object that provides the developer giving a view into the
invocation chain of a filtered request for a resource.
● FiletrConfig: It is a filter configuration object used by a servlet container to pass information
to a filter during initialization.
● FilterRegistration: It is an interface through which a Filter may be further configured.
● FilterRegistration.Dynamic: It is an interface through which a Filter registered via one of the
addFilter methods on ServletContext may be further configured.
● ReadListener: It gives us a call-back mechanism that will notify implementations as HTTP
request data.
● Registration: The interface through which a Servlet or Filter may be further configured.
● Registration.Dynamic: It is an interface through which a Servlet or Filter registered via one of
the addServlet or addFilter methods, respectively, on ServletContext may be further
configured.
● RequestDispatcher: It defines an object that receives requests from the client and sends them
to any resource on the server.
● Servlet: It defines methods that all servlets must implement.
● ServletConfig: It is a servlet configuration object used by a servlet container to pass
information to a servlet during initialization.
● ServletContainerInitializer: It notifies of a web application’s startup phase and performs any
required programmatic registration of servlets, filters, and listeners.
● ServletContext: It gives a set of methods that a servlet uses to communicate with its servlet
container.
● ServletContextAttributeListener: It receives notifications events about ServletContext
attribute changes.
● ServletContextListener: It is an interface for receiving notifications events about
ServletContext lifecycle changes.
● ServletRegistration: It is an interface through which a Servlet may be further configured.
● ServletRegistration.Dynamic: It is an interface through which a Servlet registered via one of
the addServlet methods on ServletContext may be further configured.
● ServletRequest: It defines an object to provide client request information to a servlet.
● ServletRequestAttributeListener: It is an interface for receiving notifications events about
ServletRequest attribute changes.
● ServeltRequestListener: It is an interface for receiving notifications events about requests
coming into and going out of the scope of a web application.
● ServletResponse: It defines an object to assist a servlet in sending a response to the client.
● SessionCookieConfig: It is a class that may be used to configure various properties of cookies
used for session tracking purposes.
● WriteListener: It provides a callback notification mechanism that signals to the developer it’s
possible to write content without blocking.
Package javax.servlet.http.*
It contains a number of classes and interfaces. It describes and defines the contracts between a servlet class
running under the HTTP protocol and the runtime environment.
Classes in javax.servlet.http.* package
● Cookie: It creates a cookie, a small amount of information sent by a servlet to a Web Browser,
saved by the browser, and later sent back to the server.
● HttpServlet: It provides an abstract class to be subclassed to create an HTTP servlet suitable
for a Website.
● HttpServletRequestWrapper: It provides a convenient implementation of the
HttpServletRequest interface that can be subclassed by developers wishing to adapt the
request to a Servlet.
● HttpServletResponseWrapper: It gives a convenient implementation of the
HttpServletResponse interface that can be subclassed by developers wishing to adapt the
response from a Servlet.
● HttpSessionBindingEvent: These events are either sent to an object that implements
HttpSessionBuildingListener when it is bound or unbound from a session.
● HttpSessionEvent: It is the class representing event notifications for changes to sessions
within a web application.
● Ensure you have Java JDK and an IDE like Eclipse or IntelliJ installed.
● You can either download the Servlet API JAR file and add it to your project's build path, or use a
dependency management tool like Maven or Gradle to include the Servlet API dependency in
your project.
● Create a new Java class that extends HttpServlet. This class will handle HTTP requests and
responses.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Hello, Servlet!</h1>");
response.getWriter().println("</body></html>");
deployment descriptor.
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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>
</web-app>
● Deploy your application to a Servlet container like Apache Tomcat, and then access your Servlet
at its URL, for example, http://localhost:8080/yourApp/hello.
That's it! You've created a simple Servlet program using Servlet APIs. You can expand upon this example
by handling different HTTP methods, request parameters, session management, and more.
Create HTML Form: Design an HTML form in your JSP file. This form will contain input
fields where users can enter data.
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
Create Servlet: Write a servlet to handle form submission and process the form data.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Configure Servlet Mapping: Configure your servlet in web.xml or using annotations (if
you're using Servlet 3.0+).
xml
Copy code
<servlet>
<servlet-name>ProcessFormServlet</servlet-name>
<servlet-class>com.example.ProcessFormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProcessFormServlet</servlet-name>
<url-pattern>/ProcessFormServlet</url-pattern>
</servlet-mapping>
Handle Form Data: In the servlet (ProcessFormServlet), use
request.getParameter("parameterName") to retrieve form data submitted by the user.
You can then process this data as needed (e.g., validate, save to a database, etc.).
Redirect or Forward: After processing the form data, you can redirect the user to another
servlet or JSP page using response.sendRedirect("someServlet") or forward the
request to another servlet or JSP page using
request.getRequestDispatcher("someServlet").forward(request, response).
Handling GET requests involves overriding the doGet method. The following example shows the
BookDetailServlet doing this. The methods discussed in the Requests and Responses section are shown
in italic.
The servlet extends the HttpServlet class and overrides the doGet method.
Within the doGet method, the getParameter method gets the servlet's expected argument.
To respond to the client, the example doGet method uses a Writer from the HttpServletResponse object
to return text data to the client. Before accessing the writer, the example sets the content-type header.
At the end of the doGet method, after the response has been sent, the Writer is closed.
Handling POST requests involves overriding the doPost method. The following example shows the
ReceiptServlet doing this. Again, the methods discussed in the Requests and Responses section are
shown in italic.
The servlet extends the HttpServlet class and overrides the doPost method.
Within the doPost method, the getParameter method gets the servlet's expected argument.
. Cookie Basics
Simply put, a cookie is a small piece of data stored on the client-side which servers use when
communicating with clients.
They’re used to identify a client when sending a subsequent request. They can also be used for passing
some data from one servlet to another.
Create a Cookie
To send it to the client, we need to create one and add it to the response:
We can set the max age (with a method maxAge(int)) which defines how many seconds a given cookie
should be valid for:
uiColorCookie.setMaxAge(60*60);
We set a max age to one hour. After this time, the cookie cannot be used by a client (browser) when
sending a request and it also should be removed from the browser cache.
This allows us to specify domain names to which it should be delivered by the client. It also depends on
if we specify domain name explicitly or not.
uiColorCookie.setDomain("example.com");
The cookie will be delivered to each request made by example.com and its subdomains.
If we don’t specify a domain explicitly, it will be set to the domain name which created a cookie.
For example, if we create a cookie from example.com and leave domain name empty, then it’ll be
delivered to the www.example.com (without subdomains).
Along with a domain name, we can also specify a path. Let’s have a look at that next.
If we specify a path explicitly, then a Cookie will be delivered to the given URL and all its
subdirectories:
uiColorCookie.setPath("/welcomeUser");
Implicitly, it’ll be set to the URL which created a cookie and all its subdirectories.
Now let’s focus on how we can retrieve their values inside a Servlet.
Cookies are added to the request by the client. The client checks its parameters and decides if it can
deliver it to the current URL.
We can get all cookies by calling getCookies() on the request (HttpServletRequest) passed to the Servlet.
We can iterate through this array and search for the one we need, e.g., by comparing their names:
To remove a cookie from a browser, we have to add a new one to the response with the same name,
but with a maxAge value set to 0:
A sample use case for removing cookies is a user logout action – we may need to remove some data
which was stored for an active user session.
Next, we’ll cover another important object which we access very often from a Servlet – a Session object.
3. HttpSession Object
The HttpSession is another option for storing user-related data across different requests. A session is a
server-side storage holding contextual data.
Data isn’t shared between different session objects (client can access data from its session only). It also
contains key-value pairs, but in comparison to a cookie, a session can contain object as a value. The
storage implementation mechanism is server-dependent.
A session is matched with a client by a cookie or request parameters. More info can be found here.
request.getSession(true)
In case we just want to obtain existing session and not create a new one, we need to use:
request.getSession(false)
If we access the JSP page for the first time, then a new session gets created by default. We can disable
this behavior by setting the session attribute to false:
In most cases, a web server uses cookies for session management. When a session object is created,
then a server creates a cookie with JSESSIONID key and value which identifies a session.
The session object provides a bunch of methods for accessing (create, read, modify, remove) attributes
created for a given user session:
● setAttribute(String, Object) which creates or replaces a session attribute with a key and a new
value
● getAttribute(String) which reads an attribute value with a given name (key)
● removeAttribute(String) which removes an attribute with a given name
We can also easily check already existing session attributes by calling getAttributeNames().
As we already mentioned, we could retrieve a session object from a request. When we already have it,
we can quickly perform methods mentioned above.
session.getAttribute("attributeKey");
A well-known use case for a user session is to invalidate whole data it stores when a user logs out from
our website. The session object provides a solution for it:
session.invalidate();
This method removes the whole session from the web server so we cannot access attributes from it
anymore.
HttpSession object has more methods, but the one we mentioned are the most common.
4. Conclusion
In this article, we covered two mechanism which allows us to store user data between subsequent
requests to the server – the cookie and the session.
Keep in mind that the HTTP protocol is stateless, and so maintaining state across requests is a must.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
"dbc:sqlserver://localhost\\sqlexpress:1433;databaseName=Java;encrypt=true;trustServer
Certificate=true";
response.setContentType("text/html");
// Initialize PrintWriter
try {
// Establish connection
JDBC_USER, JDBC_PASSWORD);
// Execute query
// Process result
while (resultSet.next()) {
// Output data
out.println("</body></html>");
// Close resources
resultSet.close();
preparedStatement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
Connecting directly to a database from JSP is generally not recommended due to security and
maintainability concerns. It's best practice to separate concerns and implement a proper
architecture, such as using Servlets or other server-side technologies like Spring MVC, to handle
database connectivity and operations. However, if you still want to connect to a database from
JSP for quick prototyping or educational purposes, you can follow these steps:
Include JDBC Driver: Make sure you have the JDBC driver for your database. You usually
add the JDBC driver JAR file to your project's WEB-INF/lib directory.
Establish Database Connection: Use scriptlets or JSP expression language (EL) to establish
a database connection and execute SQL queries.
Retrieve and Process Data: Execute SQL queries to retrieve data from the database and
process it within the JSP page.
Handle Exceptions: Implement error handling to deal with database connection issues
and SQL exceptions.
<html>
<head>
</head>
<body>
<%
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Establish connection
String jdbcUrl =
"jdbc:sqlserver://localhost\\sqlexpress:1433;databaseName=Java;encrypt=true;tru
stServerCertificate=true";
ResultSet rs = stmt.executeQuery(sql);
// Process result
while (rs.next()) {
out.println("<tr>");
out.println("</tr>");
out.println("</table>");
// Close resources
rs.close();
stmt.close();
e.printStackTrace();
} finally {
// Close connection
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
%>
</body>
</html>