Web Unit4 (Nep)
Web Unit4 (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.
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)
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.
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.
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.
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.
<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.
directory, and update the web.xml file, as previously described. Then, perform these steps to
test this example:
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
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:
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.
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.
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.
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:
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:
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:
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:
session.getAttribute("attributeKey");
Copy
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.
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,