0% found this document useful (0 votes)
68 views13 pages

Web Unit4 (Nep)

Uploaded by

Nishath Ashraf
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)
68 views13 pages

Web Unit4 (Nep)

Uploaded by

Nishath Ashraf
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/ 13

WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

UNIT 4
Servlets
Introduction to servlets
Today, we all are aware of the need to create dynamic web pages i.e. the ones that can
change the site contents according to the time or can generate the content according to the
request received from the client. If you like coding in Java, then you will be happy to know
that using Java there also exists a way to generate dynamic web pages and that way is Java
Servlet. But before we move forward with our topic let’s first understand the need for
server-side extensions.

Java Servlet
Java Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the web server, process the
request, produce the response, and then send a response back to the web server.
Properties of Java Servlet
The properties of Servlets are as follows:
 Servlets work on the server side.
 Servlets are capable of handling complex requests obtained from the web server.

Java Servlets Architecture


Servlet Architecture can be depicted from the image itself as provided below as follows:

Execution of Java Servlets


Execution of Servlets basically involves Six basic steps:
NANDINI S D, GFGCW, H N PURA Page 1
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

1.The Clients send the request to the Web Server.


2.The Web Server receives the request.
3.The Web Server passes the request to the corresponding servlet.
4.The Servlet processes the request and generates the response in the form of output.
5.The Servlet sends the response back to the webserver.
6.The Web Server sends the response back to the client and the client browser displays it
on the screen.
Now let us do discuss eccentric point that why do we need For Server-Side extensions?

Need of Server-Side Extensions


The Server-Side Extensions are nothing but the technologies that are used to create
dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web pages
need a container or Web server. To meet this requirement, independent Web server
providers offer some proprietary solutions in the form of APIs (Application Programming
Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java
Servlet is also one of the component APIs of Java Platform Enterprise Edition
(nowdays known as – ‘Jakarta EE’) which sets standards for creating dynamic Web
applications in Java.
Before learning about something, it’s important to know the need for that something, it’s
not like that this is the only technology available for creating Dynamic Web Pages. The
Servlet technology is similar to other Web server extensions such as Common Gateway
Interface (CGI) scripts and Hypertext Preprocessor (PHP). However, Java Servlets are
more acceptable since they solve the limitations of CGI such as low performance and low
degree scalability.

CGI(Common Gateway Interface)


CGI is actually an external application that is written by using any of the programming
languages like C or C++ and this is responsible for processing client requests and
generating dynamic content.
In CGI application, when a client makes a request to access dynamic Web pages, the Web
server performs the following operations:
 It first locates the requested web page i.e the required CGI application using URL.
 It then creates a new process to service the client’s request.
 Invokes the CGI application within the process and passes the request information to the
application.
 Collects the response from the CGI application.
 Destroys the process, prepares the HTTP response, and sends it to the client.

NANDINI S D, GFGCW, H N PURA Page 2


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

So, in CGI server has to create and destroy the process for every request. It’s easy to
understand that this approach is applicable for handling few clients but as the number of
clients increases, the workload on the server increases and so the time is taken to process
requests increases.

Servlets APIs
Servlets are built from two packages:
 javax.servlet(Basic)
 javax.servlet.http(Advance)

Various classes and interfaces present in these packages are:

Component Type Package

Servlet Interface javax.servlet.*

ServletRequest Interface javax.servlet.*

ServletResponse Interface javax.servlet.*

GenericServlet Class javax.servlet.*

HttpServlet Class javax.servlet.http.*

HttpServletRequest Interface javax.servlet.http.*

HttpServletResponse Interface javax.servlet.http.*

NANDINI S D, GFGCW, H N PURA Page 3


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Component Type Package

Filter Interface javax.servlet.*

ServletConfig Interface javax.servlet.*

Advantages of a Java Servlet


 Servlet is faster than CGI as it doesn’t involve the creation of a new process for every
new request received.
 Servlets, as written in Java, are platform independent.
 Removes the overhead of creating a new process for each request as Servlet doesn’t run
in a separate process. There is only a single instance that handles all requests
concurrently. This also saves the memory and allows a Servlet to easily manage the
client state.
 It is a server-side component, so Servlet inherits the security provided by the Web
server.
 The API designed for Java Servlet automatically acquires the advantages of the Java
platforms such as platform-independent and portability. In addition, it obviously can use
the wide range of APIs created on Java platforms such as JDBC to access the database.
 Many Web servers that are suitable for personal use or low-traffic websites are offered
for free or at extremely cheap costs eg. Java servlet. However, the majority of
commercial-grade Web servers are rather expensive, with the notable exception of
Apache, which is free.

Lifecycle of Java Servlet


Java Servlet has a pre-defined lifecycle starting from initializer (memory allocation) until
the object is destructed (memory deallocated). It takes place in following steps :
1. init() – is called as soon as the request is received by the web server and a new servlet
instance is initialized.
2. service() – to handle client request and redirect the request to an appropriate doGet() or
doPost()
3. destroy() – called when the request is handled, response sent back to the client and
finally the memory allocated to the servlet is deallocated.

Deploying a servlets
Deploying a servlet refers to the process of making a servlet available for use in a web
application. The process typically involves the following steps:
1. Create a Java class that extends the javax.servlet.http.HttpServlet class and overrides the
appropriate methods (such as doGet() or doPost()) to handle requests.
2. Compile the servlet class into a .class file using a Java compiler.
3. Package the servlet class into a JAR file, along with any other required classes and
resources.

NANDINI S D, GFGCW, H N PURA Page 4


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

4. Copy the JAR file to the appropriate location in the web application directory structure. A
Java EE web application typically uses the WEB-INF/lib directory.
5. Update the web.xml deployment descriptor to include information about the servlet, such
as its name, class name, and any initialization parameters.
6. Start the web server or application server and deploy the web application.
7. Test the servlet by sending a request to it using a web browser or other client.
The process of deploying a servlet may vary depending on the web server or application
server you are using and the specific requirements of your application.

Reading Servlet Parameters


Servlets parse the form(client) data automatically using the following methods depending on
the situation −
getParameter() − You call request.getParameter() method to get the value of a form
parameter.
getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the
current request Client pass some information from browser to web server uses GET Method
or POST Method. If a client send the data to the servlet, that data will be available in the
object of HttpServletRequest interface. In case of getParameter() method we have to pass
input parameter name and it will give the value.
request.getParameter("name")

Reading Initialization Parameters in Servlet


Both ServletContext and ServletConfig are basically the configuration objects which are
used by the servlet container to initialize the various parameter of a web application. But
they have some difference in terms of scope and availability.

Difference between ServletConfig vs. ServletContext


ServletConfig ServletContext
ServletConfig object is one per servlet ServletContext object is global to the entire
class. web application.
Object of ServletConfig will be created Object of ServletContext will be created at the
during the initialization process of the time of web application deployment
servlet.
We have to give the request explicitly in ServletContext object can be available even
order to create the ServletConfig object before giving the first request.
for the first time.

NANDINI S D, GFGCW, H N PURA Page 5


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

ServletConfig ServletContext
Scope: As long as a servlet is executing, Scope: As long as a web application is
the ServletConfig object will be available, executing, the ServletContext object will be
it will be destroyed once the servlet available, and it will be destroyed once the
execution is completed. application is removed from the server.
ServletConfig object is used while only ServletContext object is used while application
one servlet requires information shared by requires information shared by it.
it.
getServletConfig() method is used to getServletContext() method is used to obtain
obtain Servletconfig object. ServletContext object.
In web.xml — tag will be appear In web.xml — tag will be appear under tag.
under tag.

ServletConfig
An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file. If the configuration information
is modified from the web.xml file, we don't need to change the servlet. So it is easier to
manage the web application if any specific content is modified from time to time.

Methods of ServletConfig interface


public String getInitParameter(String name): Returns the parameter value for the specified
parameter name.
public Enumeration getInitParameterNames(): Returns an enumeration of all the
initialization parameter names.
public String getServletName(): Returns the name of the servlet
<web-app>
<servlet>
<servlet-name>Config</servlet-name>
<servlet-class>ConfigDemo</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>studyglance</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Config</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

NANDINI S D, GFGCW, H N PURA Page 6


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

ServletContext
ServletContext object can be used to get configuration information from web.xml file. There
is only one ServletContext object per web application. If any information is shared to many
servlet, it is better to provide it from the web.xml file using the element.

Methods commonly used in ServletContext interface


public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters.
public void setAttribute(String name,Object object):sets the given object in the application
scope.
public Object getAttribute(String name):Returns the attribute for the specified name.
<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<servlet>
<servlet-name>Context</servlet-name>
<servlet-class>ContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Context</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

Handling HTTP Requests and Responses


The HttpServlet class provides specialized methods that handle the various types of HTTP
requests. A servlet developer typically overrides one of these methods. These methods
are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
However, the GET and POST requests are commonly used when handling form input.

Handling HTTP GET Requests


Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is
defined in ColorGet.html, and a servlet is defined in ColorGetServlet.java. The HTML
source code for ColorGet.html is shown in the following listing. It defines a form that
contains a select element and a submit button. Notice that the action parameter of the form
tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.
<html>
<body>

NANDINI S D, GFGCW, H N PURA Page 7


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet>
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option> </select>
<br><br>
<input type=submit value="Submit"> </form>
</body>
</html>

The source code for ColorGetServlet.java is shown in the following listing. The doGet(
) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made by
the user. A response is then formulated.

import java.io.*; import javax.servlet.*;


import javax.servlet.http.*; Compile the servlet. Next, copy it to the appropriate
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color"); response.setContentType("text/html");
PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

directory, and update the web.xml file, as previously described. Then, perform these steps to
test this example:

Start Tomcat, if it is not already running.


Display the web page in a browser.
Select a color.
Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.

Using cookies and sessions

Cookie Basics

NANDINI S D, GFGCW, H N PURA Page 8


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

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

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);
Copy

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.

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");Copy

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.

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");Copy
NANDINI S D, GFGCW, H N PURA Page 9
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

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.

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();
}Copy

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);Copy

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.

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.

Getting a Session
We can obtain an HttpSession straight from a request:

NANDINI S D, GFGCW, H N PURA Page 10


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

HttpSession session = request.getSession();


Copy

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

request.getSession(true)Copy

In case we just want to obtain existing session and not create a new one, we need to use:

request.getSession(false)
Copy

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" %>Copy

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.

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");
Copy

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

session.getAttribute("attributeKey");
Copy

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


NANDINI S D, GFGCW, H N PURA Page 11
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

session.removeAttribute("attributeKey");
Copy

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();
Copy

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.

Connecting to a database using JDBC


To start with interfacing Java Servlet Program with JDBC Connection:
1. Proper JDBC Environment should set-up along with database creation.
2. To do so, download the mysql-connector.jar file from the internet,
3. As it is downloaded, move the jar file to the apache-tomcat server folder,
4. Place the file in lib folder present in the apache-tomcat directory.
5. To start with the basic concept of interfacing:
6.
Step 1: Creation of Database and Table in MySQL
As soon as jar file is placed in the folder, create a database and table in MySQL,

Step 2: Implementation of required Web-pages


Create a form in HTML file, where take all the inputs required to insert data into the
database. Specify the servlet name in it, with the POST method as security is important
aspects in database connectivity.

Step 3: Creation of Java Servlet program with JDBC Connection


To create a JDBC Connection steps are
1. Import all the packages
2. Register the JDBC Driver
3. Open a connection
4. Execute the query, and retrieve the result
5. Clean up the JDBC Environment
Create a separate class to create a connection of database, as it is a lame process to writing
the same code snippet in all the program. Create a .java file which returns a Connection
object.

Step 4: To use this class method, create an object in Java Servlet program
Servlet Class which create a connection and insert the data in the demo table,

NANDINI S D, GFGCW, H N PURA Page 12


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Step 5: Get the data from the HTML file


To get the data from the HTML file, the request object is used which
calls getParameter() Method to fetch the data from the channel. After successful insertion,
the writer object is created to display a success message.
After insertion operation from Servlet, data will be reflected in MySQL Database

Result : successfully inserted.

NANDINI S D, GFGCW, H N PURA Page 13

You might also like