0% found this document useful (0 votes)
25 views24 pages

Unit 6 Serverlets and JSP

Uploaded by

sudin khanal
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)
25 views24 pages

Unit 6 Serverlets and JSP

Uploaded by

sudin khanal
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
You are on page 1/ 24

Unit 6: Servlets and JSP

6.1 Overview of Web Application


6.2 HTTP Methods and Responses
6.3 Life Cycle of Web Servlets
6.4 Writing Servlet programs with Servlet APIs
6.5 Reading and Processing Forms
6.6. Handling GET/POST Requests
6.7. Database connectivity through servlets
6.8. Cookies and Sessions

6.1 Overview of Web Application:


A web application is a software application that runs on a web server and is accessed by users over
the internet through a web browser. It typically follows a client-server architecture, where the client
(web browser) sends requests to the server, and the server processes those requests and sends back
responses.

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.

6.2 HTTP Methods and Responses:


HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. It
defines methods (also referred to as verbs) that indicate the desired action to be performed on a
resource, as well as status codes that indicate the outcome of the requested action. In Java, you can
handle HTTP methods and responses using various frameworks and libraries. Here's an overview of HTTP
methods and responses in Java:

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.

Example Servlet handling GET request:

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


IOException {
// Process GET request
}

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.

Example Servlet handling POST request:

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


IOException {
// Process POST request
}

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:

2.1. Status Codes:


● HTTP status codes indicate the result of a requested action.
● Common status codes include 200 (OK), 404 (Not Found), 500 (Internal Server Error), etc.
● In Java, you can set HTTP status codes in servlets or controller methods to indicate the outcome
of the request.

Example setting status code in a servlet:

response.setStatus(HttpServletResponse.SC_NOT_FOUND); // Sets status code 404

2.2. Response Body:


● The response body contains the data returned by the server in response to a request.
● It can be HTML, JSON, XML, or any other format depending on the application.
● In Java, you can write data to the response body using the PrintWriter or other output streams.

Example writing response body in a servlet:

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>Hello, world!</body></html>");

6.3 Life Cycle of Web Servlets:


Java Servlet life cycle consists of a series of events that begins when the Servlet container loads Servlet,
and ends when the container is closed down Servlet. A servlet container is the part of a web server or
an application server that controls a Servlet by managing its life cycle. Basically there are three phases
of the life cycle.
First, the Servlet container loading Servlet in the memory, creating a servlet object and initializes it.
Second, Servlet object services requests mapped it by the Servlet container. Thirdly Servlet container
shuts down Servlet and Java Virtual Machine (JVM), which is the environment that runs Java
applications, freeing the computer resources that the Servlet.
Three of the five methods defined by the Servlet interface — init (), service () and destroy () —‘s life
cycle methods.
We’ll be covering the following topics in this tutorial:
​ The init() method:
​ The service () method
​ The destroy () method
​ Architecture Diagram of Servlet Life Cycle:

The init() method:

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.

The service() Method


The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write the
formatted response back to the client.

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.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {
}

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 doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it should be
handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}
The destroy () method

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.

6.4 Writing Servlet programs with Servlet APIs:

Java Servlet API

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.

Interfaces in javax.servlet.* package

● 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.

Interfaces in javax.servlet.http.* package

● HttpServletRequest: It helps us extend the ServletRequest interface to provide request


information for HTTP servlets.
● HttpServletResponse: It helps us extend the ServletResponse interface to provide
HTTP-specific functionality in sending a response.
● HttpSession: It provides a way to identify a user across more than a one-page request or visit
a Website and to store information about that user.
● HttpSessionActivationListener: It is an object that is bound to a session that may listen to
container events notifying them that sessions will be passivated and that session will be
activated.
● HttpSessionAttributeListener: It gives us notifications of changes to the attribute lists of
sessions within the web applications.
● HttpSessionBindingListener: Causes an object to be notified when it is bound or unbound
from a session.
● HttpSessionListener: Its implementations are notified of changes to the list of active sessions
in a web application.

Set up your development environment:

● Ensure you have Java JDK and an IDE like Eclipse or IntelliJ installed.

Create a new Java project:


● Open your IDE and create a new Java project.

Add Servlet API to your project:

● 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 Servlet class:

● 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;

public class HelloServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

response.getWriter().println("<html><body>");

response.getWriter().println("<h1>Hello, Servlet!</h1>");

response.getWriter().println("</body></html>");

Configure the Servlet in web.xml (for traditional XML-based configuration):


● If you're not using Servlet 3.0 annotations, you'll need to configure your Servlet in the web.xml

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 and run your application:

● 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.

6.5 Reading and Processing Forms:


Reading and processing forms in servlets involves similar steps to what we discussed for JSP,
with some differences in how the data is handled. Here's how you can do it:

​ Create HTML Form: Design an HTML form in your JSP file. This form will contain input
fields where users can enter data.

<form action="ProcessFormServlet" method="post">


<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>

<input type="submit" value="Submit">


</form>

​ 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;

public class ProcessFormServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");

// Process the form data (e.g., validate, save to database, etc.)

// Redirect or forward the response to another servlet or JSP page


// For example, forwarding to a success servlet
request.getRequestDispatcher("SuccessServlet").forward(request, response);
}
}

​ 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).

6.6 Handling GET and POST Requests

To handle HTTP requests in a servlet, extend the HttpServlet class and


override the servlet methods that handle the HTTP requests that your
servlet supports. This lesson illustrates the handling of GET and POST
requests. The methods that handle these requests are doGet and doPost.

Handling GET requests

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.

public class BookDetailServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title>Book Description</title></head>" +
...);

//Get the identifier of the book to display


String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
}

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

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.

public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title> Receipt </title>" +
...);
out.println("<h3>Thank you for purchasing your books from us " +
request.getParameter("cardname") +
...);
out.close();
}
...
}

The servlet extends the HttpServlet class and overrides the doPost method.

Within the doPost method, the getParameter method gets the servlet's expected argument.

6.8. Cookies and Sessions:

. 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.

For more details, please refer to this article.

Create a Cookie

The Cookie class is defined in the javax.servlet.http package.

To send it to the client, we need to create one and add it to the response:

Cookie uiColorCookie = new Cookie("color", "red");


response.addCookie(uiColorCookie);

However, its API is a lot broader – let’s explore it.

2.2. Set the Cookie Expiration Date

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.

2.3. Set the Cookie Domain

Another useful method in the Cookie API is setDomain(String).

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.

Let’s set the domain for a cookie:

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.

2.4. Set the Cookie Path

The path specifies where a cookie will be delivered.

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.

2.5. Read Cookies in the 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:

public Optional<String> readCookie(String key) {


return Arrays.stream(request.getCookies())
.filter(c -> key.equals(c.getName()))
.map(Cookie::getValue)
.findAny();
}

2.6. Remove a Cookie

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:

Cookie userNameCookieRemove = new Cookie("userName", "");


userNameCookieRemove.setMaxAge(0);
response.addCookie(userNameCookieRemove);

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.

Now we know how we can handle cookies inside a Servlet.

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.

3.1. Getting a Session

We can obtain an HttpSession straight from a request:

HttpSession session = request.getSession();


The above code will create a new session in case it doesn’t exist. We can achieve the same by calling:

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:

<%@ page contentType="text/html;charset=UTF-8" session="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.

3.2. Session Attributes

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.

We can create an attribute:

HttpSession session = request.getSession();


session.setAttribute("attributeKey", "Sample Value");

The attribute value can be obtained by its key (name):

session.getAttribute("attributeKey");

We can remove an attribute when we don’t need it anymore:


session.removeAttribute("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.

Database Connectivity through Serverlets:


To connect to an SQL database from a servlet, you typically follow these steps:
​ Import JDBC Libraries: Ensure that you have the JDBC driver for your database installed
and added to your project. You'll typically find JDBC drivers provided by the database
vendor.
​ Load the JDBC Driver: In your servlet, load the JDBC driver using
Class.forName("driverClassName"). This step is usually required only once during
application startup.
​ Establish Database Connection: Use the DriverManager.getConnection() method to
establish a connection to your database. Provide the database URL, username, and
password as parameters.
​ Execute SQL Queries: Once the connection is established, you can create a Statement or
PreparedStatement object to execute SQL queries against the database.
​ Process Results: Retrieve and process the results returned by the SQL queries as needed.
​ Close Database Resources: After you're done with the database operation, make sure to
close the database resources (Connection, Statement, ResultSet) to release database
connections and prevent resource leaks.
Here's a basic example demonstrating how to connect to an SQL database from a servlet:

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;

public class DatabaseServlet extends HttpServlet {

// JDBC URL, username, and password

private static final String JDBC_URL =

"dbc:sqlserver://localhost\\sqlexpress:1433;databaseName=Java;encrypt=true;trustServer

Certificate=true";

private static final String JDBC_USER = "username";

private static final String JDBC_PASSWORD = "password";

protected void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

// Set response content type

response.setContentType("text/html");

// Initialize PrintWriter

PrintWriter out = response.getWriter();

String title = "Database Result";

try {

// Load the JDBC driver


Class.forName("com.microoft.sqlserver.jdbc.SQLServer.Driver");

// Establish connection

Connection connection = DriverManager.getConnection(JDBC_URL,

JDBC_USER, JDBC_PASSWORD);

// Prepare SQL statement

String sql = "SELECT * FROM mytable";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

// Execute query

ResultSet resultSet = preparedStatement.executeQuery();

// Process result

out.println("<html><head><title>" + title + "</title></head><body>");

out.println("<h2>" + title + "</h2>");

while (resultSet.next()) {

// Retrieve data from result set

String column1 = resultSet.getString("column1");

String column2 = resultSet.getString("column2");

// Output data

out.println("Column 1: " + column1 + "<br>");

out.println("Column 2: " + column2 + "<br>");

out.println("</body></html>");

// Close resources

resultSet.close();

preparedStatement.close();

connection.close();
} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

out.println("Database connection error: " + e.getMessage());

Database Connectivity through JSP:

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.

Here's a basic example of connecting to a MySQL database from a JSP page:

<%@ page import="java.sql.*" %>

<%@ page import="javax.naming.*, javax.sql.*" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

<title>Database Connection in JSP</title>

</head>

<body>

<h2>Database Connection in JSP</h2>

<%
Connection conn = null;

try {

// Load the JDBC driver

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Establish connection

String jdbcUrl =

"jdbc:sqlserver://localhost\\sqlexpress:1433;databaseName=Java;encrypt=true;tru

stServerCertificate=true";

String username = "your_username";

String password = "your_password";

conn = DriverManager.getConnection(jdbcUrl, username, password);

// Execute SQL query

Statement stmt = conn.createStatement();

String sql = "SELECT * FROM mytable";

ResultSet rs = stmt.executeQuery(sql);

// Process result

out.println("<table border='1'><tr><th>Column 1</th><th>Column 2</th></tr>");

while (rs.next()) {

out.println("<tr>");

out.println("<td>" + rs.getString("column1") + "</td>");

out.println("<td>" + rs.getString("column2") + "</td>");

out.println("</tr>");

out.println("</table>");

// Close resources

rs.close();
stmt.close();

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

out.println("Database connection error: " + e.getMessage());

} finally {

// Close connection

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

%>

</body>

</html>

You might also like