0% found this document useful (0 votes)
174 views25 pages

Java Servlet Basics: RequestDispatcher & Cookies

The document is about More Academy, an educational institution located in Mumbai, India that provides training in enterprise Java. It contains notes on the RequestDispatcher interface in Java servlets, which provides the ability to dispatch requests to other resources like HTML, servlets, or JSPs. It also allows including the content of other resources. The interface has methods like getRequestDispatcher() and getNamedDispatcher() to obtain a RequestDispatcher object. It also discusses cookies in Java servlets. Cookies are text files stored on a user's computer that are used for tracking purposes. There are non-persistent and persistent cookies, with non-persistent cookies expiring when the browser closes and persistent cookies remaining until expired or deleted

Uploaded by

Aman Jaiswal
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)
174 views25 pages

Java Servlet Basics: RequestDispatcher & Cookies

The document is about More Academy, an educational institution located in Mumbai, India that provides training in enterprise Java. It contains notes on the RequestDispatcher interface in Java servlets, which provides the ability to dispatch requests to other resources like HTML, servlets, or JSPs. It also allows including the content of other resources. The interface has methods like getRequestDispatcher() and getNamedDispatcher() to obtain a RequestDispatcher object. It also discusses cookies in Java servlets. Cookies are text files stored on a user's computer that are used for tracking purposes. There are non-persistent and persistent cookies, with non-persistent cookies expiring when the browser closes and persistent cookies remaining until expired or deleted

Uploaded by

Aman Jaiswal
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

www.moreacademy.

online

More Academy

ENTERPRISE JAVA
SEM: V
SEM V: UNIT 2

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


MORE ACADEMY BSC IT: SEM – V JAVA: U2

Page 1 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

1. Write a short note on RequestDispatcher Interface (NOV 18, APR 19 , NOV 19 , NOV 22)

In the Javax.servlet package, the RequestDispatcher interface provides the facility of dispatching
the request to another resource , be it html, servlet or jsp. This interface can also be used to include
the content of another resource.
For obtaining the object, two styles exist using ServletRequest object and ServletContext object. The
getRequestDispatcher(String path) method returns an object of Request Dispatcher and the same
method exist in both interfaces of ServletRequest and ServletContext. This can be chived like
following:

• javax.servlet.ServletContext.getRequestDispatcher(String path)

• javax.servlet.ServletRequest.getRequest Dispatcher(String path)


• RequestDispatcher getRequestDispatcher(String path): Returns a RequestDispatcher
object that acts as a wrapper for the resource located at the given path. A
RequestDispatcher object can be used to forward a request to the resource or to include
the resource in a response. The resource can be dynamic or static.

• Request Dispatcher getNamed Dispatcher(String name): This method takes the name of
the Servlet (and JSP pages also) as parameter which is declared via Deployment
descriptor. It expects logical name of the destination servlet/JSP program as argument
value.
METHODS OF REQUESTDISPATCHER
Request Dispatcher is used in two cases:
• To include the response (output) of one Servlet into another (that is, client gets the response of
both Servlets).
• To forward the client request to another Servlet to honour (that is, client calls a Servlet but
response to client is given by another Servlet).

Forward() method:

Include() method

Page 2 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

2. What is a Cookie? Explain its types. (APR 23)


Cookies are text files stored on the customer's computer and are saved for various information
tracking purposes. Java Servlet transparently supports HTTP cookies.
There are three steps involved in identifying recurring users:
The server script sends a series of cookies to the browser. For example, name, age or identification
number, etc.
The browser stores this information on the local machine for future use.
The next time the browser sends a request to the web server, it will send the cookie information to
the server and the server will use that information to identify you.
A servlet will access the cookie via the request.getCookies () request method which returns an array
of Cookie objects.
Some of the common uses of cookies are:
1. Session authentication uses cookie.
2. Personalized response to the customer based on their preferences, for example, we can set the
background color as a cookie in the customer's browser and then use it to customize the background
color of the response, image, etc.

Types of cookies:

There are 2 types of cookies in servlets:

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie: It is valid for one session only. It is removed every time the user closes the
browser. A non-persistent cookie, also known as a session cookie or in-memory cookie, is a type of
HTTP cookie that is temporarily stored in a user's web browser's memory while the user is actively
using a website. Unlike persistent cookies, which have an expiration date and are stored on the user's
device for a specified period, non-persistent cookies are short-lived and exist only for the duration of a
user's session on a website.

Persistent cookie: It is valid for multiple sessions. It is not removed every time the user closes the
browser. It is removed only if the user logs out or logs out. A persistent cookie, also known as a
permanent cookie or a long-term cookie, is a type of HTTP cookie that is stored on a user's device for
an extended period, beyond the duration of their current session on a website. Unlike non-persistent
(session) cookies, which are temporary and stored in memory, persistent cookies are written to the
user's hard drive and remain there until they expire or are manually deleted by the user.

In summary, persistent cookies are a type of HTTP cookie that is stored on a user's device for an
extended period, allowing websites to remember user data and preferences across different sessions.
While they are valuable for enhancing user experiences and providing long-term functionality, their
use is subject to privacy regulations and user consent requirements.

Page 3 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

3. Write a short note on HttpSession.


The HTTP protocol is stateless, so we need to maintain state through session tracking techniques.
Each time the user requests the server, the server treats the request as a new request. Therefore, we
need to maintain a user's status to recognize a particular user.
HTTP is stateless, which means that each request is treated as the new request.
All requests and responses are independent. But sometimes it is necessary to monitor customer
activity on multiple requests. For example. When a user logs into your website, regardless of which
web page they visit after logging in, their credentials will remain on the server until they log off. Then
this is handled by creating a session.

`HttpSession` is a Java technology used in web applications to maintain session state and store user-
specific data between multiple HTTP requests and responses. It is a part of the Java Servlet API and
serves as a server-side session management mechanism. Here are some key points about
`HttpSession`:

1. Session Management: `HttpSession` allows web applications to create and manage user sessions.
A session is a logical association between a user and the web application, often spanning multiple
HTTP requests and responses.

2. User Identification: Sessions are typically used to identify and track individual users as they
interact with a web application. When a user visits a website, a unique session identifier (session ID) is
assigned to them, which is stored as a cookie or included in the URL.

3. Data Storage: `HttpSession` provides a way to store user-specific data as attributes within the
session. These attributes can be accessed and modified throughout the user's session, making it
possible to maintain user-related information like login credentials, shopping cart contents, and user
preferences.

4. Attribute Storage: Attributes stored in an `HttpSession` are often implemented as key-value pairs,
where the key is a string and the value can be any Java object. This flexibility allows developers to
store a wide range of data types.

5. Lifecycle: HttpSession has a defined lifecycle. It is created when a user first accesses a web
application and is associated with a session ID. It remains active as long as the user interacts with the
application and expires after a configurable period of inactivity or when the user logs out.

6. Scope: HttpSession attributes have session scope, meaning they are accessible throughout the
user's session but are not shared across different users or sessions. This makes it a suitable choice for
maintaining user-specific data.

7. Methods: HttpSession provides methods for creating, accessing, and managing session attributes.
Common methods include `setAttribute()`, `getAttribute()`, `removeAttribute()`, and `invalidate()` (to
end the session).

Overall, `HttpSession` is a fundamental component of Java web applications, enabling the


management of user sessions and the storage of user-specific data. It plays a crucial role in providing
a stateful and interactive experience to users while adhering to web security and privacy standards.

Page 4 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

4. Explain various steps comprising life cycle of HttpSession. (NOV 18)


Session life cycle:
• A visitor, using a web browser, requests a resource from the web server.
• The web server offers the authentication form which causes the visitor's web browser to display a login form.
• The web browser returns the username and password, which are then returned to the web server.
• The web server returns a valid session ID to uniquely identify this visitor.
• The visitor's web browser sends any number of requests to the web server. The web server identifies users
based on session IDs.
• The visitor closes the browser without explicitly logging out.

Session Monitoring API:


The session monitoring API is based on the first four methods. This is to help the developer minimize
the overhead of session monitoring. This type of session tracking is provided by the underlying
technology. Let's take the example of the Java servlet. The servlet container handles session tracking
activity and the user does not need to explicitly do this using Java servlets. This is the best of all
methods, because all handling and errors related to session monitoring will be handled by the
container itself.

Session Monitoring Methods:


• User authentication: This is the very common way that the user can provide authentication credentials from
the login page and then we can pass the authentication information between the server and the client to
maintain the session. This is not a very effective method because it will not work if the same user is logged in
from different browsers.
• HTML hidden field: We can create a unique hidden field in the HTML and when the user
starts browsing we can set its unique value for the user and keep track of the session.
This method cannot be used with bindings because it requires the form to be submitted
each time a client-to-server request is made with the field hidden. Also, it's not safe
because we can get the hidden field value from the HTML source and use it to hack the
session.
• URL rewrite: We can add a session identifier parameter with each request and response
to keep track of the session. This is very tedious because we have to keep track of this
parameter in every response and make sure it doesn't collide with other parameters.
• Cookies: Cookies are small pieces of information sent by the web server in the response
header and stored in the browser's cookies. When the client makes an additional
request, it adds the cookie to the request header and we can use it to track the session.
We can maintain a session with cookies, but if the client disables cookies, it will not
work.

Session Management API:


The Session Management API builds on the previous methods for session monitoring. Some of the
major disadvantages of all of the above methods are:
1. Most of the time we don't just want to keep track of the session, we need to store some data in the
session that we can use in future requests. This will require a lot of effort if we try to implement it.
2. All of the above methods are not complete by themselves, they will not all work in a particular
scenario. So we need a solution that can use these session tracking methods to provide session
management in all cases.

Page 5 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

5. Explain the methods of cookie class that facilitative the creation, manipulation and deletion
of the cookies. (NOV 18, APR 19, NOV 22)

(1)Creation of a Cookie object: You call the cookie constructor with a cookie name and a cookie
value, both are strings.

Cookie cookie = new Cookie ("name", "value"); Note that neither the name nor the value must
contain spaces or any of the following characters: [] () =, "/? @:;
In Java, you can create a `Cookie` object from the `javax.servlet.http` package to work with HTTP
cookies in a web application. Here's how you can create a `Cookie` object:

You import the `javax.servlet.http.Cookie` class, which is part of the Java Servlet API and provides
functionality for working with HTTP cookies.

You create a new `Cookie` object named `myCookie` using the `Cookie` constructor. The constructor
takes two parameters:
- The first parameter is the name of the cookie (a string). This name is used to identify the cookie.
- The second parameter is the value of the cookie (also a string). This is the data you want to store
in the cookie.

After creating the `Cookie` object, you can further configure it by setting various properties such as
the cookie's path, domain, expiration date, and whether it should be sent securely over HTTPS.
Here's an example of how to set some common properties:```

Adding the `Cookie` to the response will instruct the client's browser to store the cookie and send it
back to the server with subsequent HTTP requests, allowing you to maintain state or store user-
specific information.

(2) Set the maximum age: Use setMaxAge to specify how long (in seconds) the cookie should be
valid.
The following would set a cookie for 24 hours. cookie.setMaxAge (60 * 60 * 24);

(3) Sending the cookie to the HTTP response headers: Use response.addCookie to add cookies in
the HTTP response header as follows
response.addCookie (cookie);

(4) Removing Cookies


Sometimes you may want to remove a cookie from the browser. You do so by setting the cookie
expiration time. You can set the expiration time to 0 or -1. If you set the expiration time to 0 the cookie
will be removed immediately from the browser. If you see the expiration time to -1 the cookie will be
deleted when the browser shuts down.
Cookie cookie = new Cookie("uid", "");
cookie.setMaxAge(0);
response.addCookie(cookie);

Page 6 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

6. What is Non-Blocking I/O? Explain WriteListener and ReadListener performing in Non-


Blocking I/O? (NOV 18, APR 23)

Non-blocking I/O was introduced in Servlet 3.1to develop scalable applications, Servlet 3.0 allowed
asynchronous request processing, but the API allowed only traditional 1/0, which can restrict scalability
of your applications. In a typical application, ServletInputStream is read in a while loop. However, if the
incoming data is blocked or is streamed slower, the server thread must wait for the data. The same
situation can happen if the data is written to ServletOutputStream.
Servlet 3.1 resolves the problem by adding event listeners: ReadListener and WriteListener interfaces.
You register these event listeners by using ServletInputStream.setReadListener and
ServletOutputStream.setWriteListener.
The listeners have callback methods that are invoked when the content is available to be read or that
can be written without blocking.
The main idea of these technologies is to avoid threads blocking. That's important because blocked
threads waste resources, threads' memory and processor time during threads context switching. So in
some cases it's possible to increase servlet performance without any costs.

ReadListener and WriteListener :

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.Linked BlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener,
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;

public class ReadListenerImpl implements ReadListener {

private ServletInputStream input = null; private HttpServletResponse res = null;

private AsyncContext ac = null;

private Queue queue = new LinkedBlockingQueue();

ReadListenerImpl(ServletInputStream in, HttpServletResponse r, AsyncContext c)


{
input = in:
res = r;
ac = c;
}
public void onDataAvailable() throws IOException {

System.out.println("Data is available"); StringBuilder sb = new StringBuilder();

int len = -1;

byte b[] = new byte[1024];

while (input.isReady() && (len = input.read(b)) != -1) {


String data= new String(b, 0, len); sb.append(data);
}

Page 7 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

queue.add(sb.toString());
}
public void onAllDataRead() throws IOException
{ System.out.println("Data is all read");

// now all data are read, set up a WriteListener to write


ServletOutputStream output = res.getOutputStream(); WriteListener writeListener = new
WriteListenerImpl(output, queue, ac); output.setWriteListener(writeListener);
}
public void onError(final Throwable t) {

ac.complete();

t.printStackTrace();
}
}

Page 8 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

7. Explain the working of Non-Blocking I/O. (NOV 18, APR 19, NOV 22)

Non-blocking I/O (Input/Output), also known as asynchronous I/O, is a programming paradigm and
I/O model that allows applications to perform I/O operations without waiting for the operation to
complete. In traditional blocking I/O, a program typically blocks (waits) until data is ready to be read
from or written to a file, socket, or other I/O source. In contrast, non-blocking I/O enables an
application to continue executing other tasks while waiting for I/O operations to finish. Here's an
explanation of how non-blocking I/O works:

The basic flow for a servlet that calls an external REST service using an async HTTP client (for example
AsyncHttpClient) looks like this:

1. First of all the servlet where we want to provide async support should have @WebServlet
annotation with asyncSupported value as true.

2. Since the actual work is to be delegated to another thread, we should have a thread pool
implementation. We can create thread pool using Executors framework and use servlet context
listener to initiate the thread pool.

3. We need to get instance of AsyncContext through ServletRequest.startAsync() method.


AsyncContext provides methods to get the ServletRequest and ServletResponse object references.
It also provides method to forward the request to another resource using dispatch() method.

4. We should have a Runnable implementation where we will do the heavy processing and then use
AsyncContext object to either dispatch the request to another resource or write response using
ServletResponse object. Once the processing is finished, we should call AsyncContext.complete()
method to let container know that async processing is finished.

5. We can add AsyncListener implementation to the AsyncContext object to implement callback


methods, we can use this to provide error response to client in case of error or timeout while async
thread processing. We can also do some clean-up activity here.

Page 9 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

8. Explain about the file uploading feature of a servlet. (NOV 18)

The term "upload" refers to the process of transferring data or files from a local or client-side
computer or device to a remote or server-side computer or server. This transfer is typically
performed over a network, such as the internet, and it allows users to share, send, or store files on
a remote server. Uploads are the opposite of downloads, where data or files are transferred from a
remote server to a local device.

Uploading Files:

Upload is a used to describe the process of transferring (sending) a file to another computer through
a modem or network. Below are a few examples of how a file may be uploaded to another computer.

Examples of an Uploaded file:


• Over a network: If you are connected to a network you can upload a file to another computer or share using
file sharing.

• Over FTP, Telnet, or SSH: If you want to share something on the Internet, or have a personal web page, you
would upload the files to a computer or server connected to the Internet. FTP is the most common method of
uploading files.

Supporting file uploads is a very basic and common requirement for many web applications. The
Servlet 3.0 specification supports file upload out of the box, so any web container that implements the
specification can parse multipart requests and make mime attachments available through the
HttpServletRequest object.

A new annotation, javax.servlet.annotation.MultipartConfig, is used to indicate that the servlet on


which it is declared expects requests to made using the multipart/form-data MIME type. Servlets that
are annotated with @MultipartConfig can retrieve the Part components of a given multipart/form-data
request by calling the request.getPart(String name) or request.getParts() method.

Page 10 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

9. Explain using a code snippet the onDataAvailable() and onAllDataRead() methods of


ReadListener interface. (NOV 19, APR 23)

onDataAvailable is called when data can be read without blocking.


onAllDataRead is invoked when data for the current request is completely read.
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.Linked BlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener,
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;

public class ReadListenerImpl implements ReadListener {

private ServletInputStream input = null; private HttpServletResponse res = null;

private AsyncContext ac = null;

private Queue queue = new LinkedBlockingQueue();

ReadListenerImpl(ServletInputStream in, HttpServletResponse r, AsyncContext c)


{
input = in:
res = r;
ac = c;
}
public void onDataAvailable() throws IOException {

System.out.println("Data is available"); StringBuilder sb = new StringBuilder();

int len = -1;

byte b[] = new byte[1024];

while (input.isReady() && (len = input.read(b)) != -1) {


String data= new String(b, 0, len); sb.append(data);
}
queue.add(sb.toString());
}
public void onAllDataRead() throws IOException
{ System.out.println("Data is all read");

// now all data are read, set up a WriteListener to write


ServletOutputStream output = res.getOutputStream(); WriteListener writeListener = new
WriteListenerImpl(output, queue, ac); output.setWriteListener(writeListener);
}
public void onError(final Throwable t) {
ac.complete();
t.printStackTrace();
}
}

Page 11 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

10. Explain the following w. r. t. working with files in Servlet. (Reference Book Page No.- 323)
(NOV 19)

i) @MultipartConfigure - This annotation is used to indicate that the Servlet on which it is


declared expects requests to made using the multipart/form-data MIME type. We need to
annotate File Upload handler servlet with MultipartConfig annotation to handle
multipart/form-data requests that is used for uploading file to server.
The term "@MultipartConfigure" appears to be a reference to a configuration or annotation
used in the context of Java web development, particularly when dealing with multipart form
data. However, it's important to note that there is no standard annotation or configuration in
Java or Java EE with this specific name.

To handle multipart form data, such as file uploads, in a Java web application, developers
often use libraries like Apache Commons FileUpload or the built-in capabilities of modern
web frameworks like Java Servlets or Spring Framework. These libraries provide
annotations or configuration options to specify how multipart requests should be processed.
may vary depending on the framework or library being used. If you

ii) fileSizeThreshold - This attribute Specify size threshold when saving the upload file
temporarily. If the upload file's size is greater than this threshold, it will be stored in disk.
Otherwise the file is stored in memory. Size in bytes. Defaults is 0.

iii) location - This attribute Specify directory where upload files are stored. Default

iv) maxFileSize - This attribute Specify maximum size of an upload file. Size in bytes. Defaults
is -1L

The `maxFileSize` attribute, typically found in configurations for handling multipart form data
in Java web applications, specifies the maximum allowable size (in bytes) for an individual file that
can be uploaded through a multipart request. Multipart requests are commonly used for file uploads
in web applications.

v) maxRequestSize - This attribute Specify maximum size of a request (including both upload
files and other form data). Size in bytes. Defaults is -1L.
The `maxRequestSize` attribute, often found in configurations for handling multipart form
data in Java web applications, specifies the maximum allowable size (in bytes) for the entire
multipart request. This attribute sets an upper limit on the combined size of all the files and
data included in a single multipart request.

Page 12 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

11. Write a servlet program GradeServlet.java that accepts Grade through radio buttons from
index.html page, if the string is “A”, “B”, “C” OR “D”, the program should dispatch the direct
to the Success.html page containing message “Congratulations, You Passed SEM V exam”,
else display “Try Again” and load index.html page in current servlet. (NOV 19)

import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet{
public void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
PrintWriter pw = hres.getWriter();
String inp = hreq.getParameter("grade");
if(inp.equals("A") || inp.equals("B") || inp.equals("C") || inp.equals("D") )
{
RequestDispatcher rd = hreq.getRequestDispatcher("Success.html");
rd.forward(hreq, hres);
}
else {
out.println("<H1>TRY Again </h1>");
RequestDispatcher rd = hreq.getRequestDispatcher("index.html");
rd.include(hreq, hres);
}
}

Page 13 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

12. Write a servlet program to create a session and display the following:
i) Session ID
ii) New or Old
iii) Creation Time (NOV 19)

import java.io.*;

import javax.servlet.*;

import javax.servelt.http.*;

public class Test extends HttpServlet{

public void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws

ServletException, IOException{

PrintWriter pw = hres.getWriter();

HttpSession hs = hreq.getSession(true);

out.println("<br>Session ID "+ hs.getId());

out.println("<br>Is New "+ hs.isNew());

out.println("<br>Creation Time "+ new java.util.Date(hs.getCreationTime()));

Page 14 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

13. Explain Cookie class with its constructor and any five methods. (NOV 19, APR 23)
Cookies are small pieces of information sent by the web server in the response header and stored
in the browser's cookies. When the client makes an additional request, it adds the cookie to the
request header and we can use it to track the session. We can maintain a session with cookies, but if
the client disables cookies, it will not work.
Cookie() – Creating a Cookie Constructor

To creates a cookie Cookie() constructor is used, a small amount of information sent by a servlet to a
Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely
identify a client, so cookies are commonly used for session management.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they
handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.
The servlet sends cookies to the browser by using the
HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP
response headers to send cookies to the browser, one at a time. The browser is expected to support
20 cookies for each Web server, 300 cookies total, and cookie size to 4 KB each. may limit

Syntax: public Cookie(java.lang.String name, java.lang.String value)


It constructs a cookie with a specified name and value.
Cookie (string name, string value) - constructs a cookie with a specified name and value.
public void setDomain (string schema)
• This method sets the domain to which the cookie applies, for example google.com.
public String getDomain ()
• This method gets the domain to which the cookie applies, for example google.com.
public void setMaxAge (expiration int)
• This method sets the time (in seconds) that must elapse before the cookie expires.
public int getMaxAge ()
• This method returns the maximum age of the cookie, specified in seconds. By default, -1 indicates that the
cookie will persist until the browser is deactivated.
public String getName ()
• This method returns the name of the cookie. The name cannot be changed after creation.

Page 15 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

14. What is session tracking? What are the ways to track the sessions? (APR 19, APR 23)

Session tracking is a mechanism used in web development to maintain stateful interactions between a
web server and a web client (usually a web browser) across multiple HTTP requests and responses. It
allows web applications to associate a user's actions and data with a specific session, enabling the
retention of user-specific information and providing a continuous and personalized user experience.

Session tracking is crucial for various purposes, such as user authentication, shopping cart management,
remembering user preferences, and tracking a user's progress through a multi-step process (e.g., a
checkout process in an e-commerce site).
The choice of session tracking method depends on factors such as security requirements, user
preferences, and the technology stack used in the web application. Many applications use a combination of
these methods to ensure robust session tracking and a seamless user experience.

Session tracking is a mechanism that servlets use to maintain state about a series of requests from
the same user (that is, requests originating from the same browser) across some period of time.
Sessions are shared among the servlets accessed by a client. This is convenient for applications
made up of multiple servlets.
The javax.servlet.http package contains a number of classes and interfaces that describe and define
the contracts between a servlet class running under the HTTP protocol and the runtime environment
provided for an instance of such a class by a conforming servlet container.
The interface HttpSession provides a way to identify a user across more than one page request or
visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP
server. The session persists for a specified time period, across more than one connection or page
request from the user. A session usually corresponds to one user, who may visit a site many times.
The server can maintain a session in many ways such as using cookies or rewriting URLs.
This interface allows servlets to:

• View and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.

• Bind objects to sessions, allowing user information to persist across multiple user connections.

Page 16 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

15. Write short note on creation and invalidation of sessions. (APR 19)
By default every web server will have a configuration set for expiry of session objects.
Generally it will be some X seconds of inactivity. That is when the user has not sent any request to
the server for the past X seconds then the session will expire. When a session expires, the
HttpSession object and all the data it contains will be removed from the system. When the user
sends a request after the session has expired, server will treat it as a new user and create a new
session.
Apart from that automatic expiry, it can also be invalidated by the user explicitly. HttpSession
provides a method invalidate() this unbinds the object that is bound to it. Mostly this is used at
logout. Or the application can have an absurd logic like after the user logins he can use the
application for only 30 minutes. Then he will be forced out. In such scenario you can use
getCreation Time().

Creation of a Session

In web applications, a session is created to maintain state and user-specific data across multiple
HTTP requests and responses. The creation of a session involves several steps:

1. Client Request: The process begins when a user interacts with a web application by sending an
HTTP request to the server. This request can be triggered by various actions, such as visiting a
website, logging in, or performing an action that requires session tracking.

2. Server Recognition: Upon receiving the user's request, the web server checks if a session
already exists for the user. Sessions are often identified by a unique session ID, which is typically
stored on the client side (e.g., as a cookie) or transmitted in the request (e.g., as a URL parameter).
The server uses this ID to recognize the session.

3. Session Existence Check: If the server does not find a valid session ID in the request or if the
session has expired, it assumes that a new session needs to be created for this user.

4. Session Initialization: To create a new session, the server generates a unique session ID. This
ID is used to associate all subsequent requests from the same user with this session.

Invalidation of Sessions in Web Applications

In web applications, sessions are used to maintain user-specific data and state across multiple HTTP
requests. However, there are circumstances where sessions need to be invalidated or ended. The process
of ending a session is known as session invalidation. Here's how sessions can be invalidated in web
applications:

1. **Explicit Logout**: One of the most common ways to invalidate a session is through an explicit logout
action initiated by the user. When a user logs out of a web application, the application typically performs the
following steps:

- The server marks the user's session as "invalid" or "logged out."


- Session data associated with the user is cleared or reset to its initial state.
- Any authentication tokens or credentials are invalidated, preventing further access without
reauthentication.
- The user is redirected to a logout confirmation page or the application's homepage.

2. Session Timeout: Sessions in web applications often have a configurable timeout period. If a user
remains inactive for a specified duration (e.g., 30 minutes), the session can automatically expire due to a
timeout. When a session times out:

Page 17 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

- The session is marked as invalid or expired by the server.


- Session data is cleared or reset.
- The user may need to log in again to create a new session.

3. Manual Invalidation: In some cases, web applications may manually invalidate sessions based on
specific criteria. For example:

- A session might be invalidated if a user's account is disabled or deleted.


- After a certain period of inactivity, the application might automatically invalidate the session to free up
server resources.
- Security-related events, such as a password change, might trigger session invalidation to ensure that
any old authentication tokens are no longer valid.

4. Session ID Change: For security purposes, some applications periodically change the session ID
associated with a user's session. When the session ID changes:

- The old session is effectively invalidated.


- A new session is created for the user with a new session ID.
- Session data is migrated to the new session as needed.

Page 18 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

16. Which points are important while uploading a file? (APR 19)
The following are the important points to note:
The form method attribute must be set to POSTmethod and the GET method cannot be used.
The choice between using the POST and GET methods in an HTML form depends on the
specific requirements of the form and the type of interaction you want to achieve in your web application.
Both methods have their use cases and characteristics:

1. POST Method:
- In the POST method, form data is submitted to the server as part of the HTTP request body.
- It is suitable for submitting sensitive or large amounts of data, such as login credentials, file uploads, or
lengthy form submissions.
- Data submitted via POST is not visible in the URL, which can enhance security and privacy.
- POST requests can include binary data, making it suitable for file uploads.
- It is the preferred method for actions that modify server-side data, such as creating, updating, or
deleting records in a database.

2. GET Method:
- In the GET method, form data is appended to the URL as query parameters.
- It is suitable for simple, non-sensitive data submissions, such as search queries or filtering options.
- Data submitted via GET is visible in the URL, which can be bookmarked and shared easily but may
pose privacy concerns for sensitive data.
- GET requests are idempotent, meaning they should not have side effects on the server. They are
typically used for read-only operations.
- GET requests are often cached by browsers and proxies, which can improve performance for repetitive
requests.

```

It is not accurate to say that the form method attribute "must" be set to POST or that GET "cannot" be used.
The choice between POST and GET depends on the specific requirements of your form and how you want
to handle the submitted data. You should consider factors such as data sensitivity, data size, security, and
the desired behavior of your application when determining which method to use. In practice, both POST
and GET methods have their place in web development and are used as appropriate for different
scenarios.
The form enctype attribute must be set to multipart / form-data.
The module action attribute should be set to a servlet file that would handle uploading files to the backend
server. The following example uses the UploadServlet servlet to upload the file.
To upload a single file, you need to use a single <input…/> with attribute type = "file". To allow multiple file
uploads, include more than one input tag with different values for the name attribute. The browser
associates each of them with a Browse button.

Page 19 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

17. Write a servlet code to download a file. (NOV 22)

SERVLET CODE:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
private static final String FILE_PATH = "path/to/your/file.txt"; // Replace with the actual file path

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Get the file name from the path
String fileName = new File(FILE_PATH).getName();

// Set the content type and headers for the response


response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

// Read the file and write its contents to the response output stream
try (FileInputStream fileInputStream = new FileInputStream(FILE_PATH)) {
int i;
while ((i = fileInputStream.read()) != -1) {
response.getWriter().write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Page 20 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

18. Which things needs to be carefully checked and understood while writing file uploading
code in servlet? (NOV 22)

When writing file upload code in a servlet, there are several important considerations and
potential pitfalls that you should be aware of to ensure the security, reliability, and performance of
your application. Here are the key things to carefully check and understand:

1. Security Concerns:

- File Validation: Always validate uploaded files to ensure they meet your expected criteria in
terms of file type, size, and content. Never trust user-submitted file information.

- File Type Checking: Check the file's MIME type to prevent malicious uploads. Don't rely solely
on the file extension, as it can be easily manipulated.

- File Size Limit: Set a reasonable limit on the file size to prevent denial-of-service attacks by
uploading large files that consume server resources.

- File Overwriting: Ensure that an uploaded file with the same name doesn't overwrite an
existing file unintentionally.

- File Permissions: Be careful with file permissions on the server to prevent unauthorized
access to uploaded files.

2. Multipart Form Data Handling:

- Use a library or built-in servlet container support to handle multipart form data. Most commonly,
developers use libraries like Apache Commons FileUpload or Servlet 3.0's built-in multipart
support.

3. Form Configuration:

- Ensure that your HTML form has the `enctype` attribute set to `"multipart/form-data"`. Without
this, file uploads won't work.

```html
<form action="/UploadServlet" method="post" enctype="multipart/form-data">
<!-- File input field and other form elements -->
</form>
```

4. File Storage:

- Decide where and how you want to store uploaded files. You can store them on the server's file
system, in a database, or in a cloud storage solution like Amazon S3.

- Be mindful of the file system location and directory structure where you save the files. Avoid
storing uploaded files in sensitive directories or allowing direct access to them.

Page 21 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

5. File Name Sanitization:

- Sanitize file names to remove potentially harmful characters or escape them to prevent
directory traversal attacks.

6. Error Handling:

- Implement error handling for file upload failures, such as disk space issues or file I/O errors.

7. Performance Considerations:

- Large File Handling: Consider how your application will handle large file uploads, as these can
impact server resources and response times.

- Asynchronous Processing: For large file uploads, consider using asynchronous processing to
offload the upload process from the main application thread.

8. Network Considerations:

- Be aware that file uploads can consume significant bandwidth, especially if multiple users
upload large files simultaneously. Ensure your server and network can handle this traffic.

9. Testing and Validation:

- Thoroughly test your file upload functionality under various scenarios, including uploading files
of different sizes and formats.

- Test for concurrent uploads and ensure your servlet can handle multiple requests
simultaneously.

10. Logging and Monitoring:

- Implement proper logging and monitoring to keep track of file upload activities, errors, and
security-related events.

By carefully addressing these considerations, you can create a secure and reliable file upload
feature in your servlet-based web application. Additionally, staying updated on security best
practices and regularly reviewing your code for potential vulnerabilities is crucial.

Page 22 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

19. Write a program in servlet application to upload file.

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.http.*;

import com.oreilly.servlet.MultipartRequest;

public class UploadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

MultipartRequest m=new MultipartRequest(request,"d:/new");

out.print("successfully uploaded");

Page 23 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U2

Page 24 of 24
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622

You might also like