Java Servlet Basics: RequestDispatcher & Cookies
Java Servlet Basics: RequestDispatcher & Cookies
online
More Academy
ENTERPRISE JAVA
SEM: V
SEM V: UNIT 2
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)
• 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
Types of cookies:
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
`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).
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
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);
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
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.
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;
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");
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.
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.
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
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.
• 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.
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
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)
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.*;
ServletException, IOException{
PrintWriter pw = hres.getWriter();
HttpSession hs = hreq.getSession(true);
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
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.
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:
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
3. Manual Invalidation: In some cases, web applications may manually invalidate sessions based on
specific criteria. For example:
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:
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
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
// 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.
- 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
- 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.
- 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.
- 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
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.oreilly.servlet.MultipartRequest;
response.setContentType("text/html");
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