Unit 2 Notes For Internal Test
Unit 2 Notes For Internal Test
Chapter 7
ADITI CHIKHALIKAR 1
2. Give suitable example to explain the methods of the RequestDispatcher interface. U
ANSWER:
o There are two methods defined in the RequestDispatcher interface
o 1. public void forward(ServletRequest request,ServletResponse response) throws
ServletException, IOException: Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the server.
o 2. public void include(ServletRequest request,ServletResponse response) throws
ServletException, IOException: Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.
index.html
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="POST">
<br> <hr> <br>
Enter USERNAME:<input type="text" name="txtUname"><br> <br>
Enter PASSWORD:<input type="password" name="txtPwd"><br>
<br> <hr> <br>
<input type="submit" value="Login">
<input type="reset" value="Reset">
<br> <hr> <br>
</form>
</body>
</html>
LoginServlet.java
package DemoServlet2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
String uname=request.getParameter("txtUname");
String pass=request.getParameter("txtPwd");
if(pass.equals("servlet"))
{
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
ADITI CHIKHALIKAR 2
rd.forward(request, response);
}
else
{
out.println("<h1>Login failed!! Try again</h1>");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
package ServletDemo2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends
HttpServlet {
protected void service (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
String name=request.getParameter("txtUname");
PrintWriter out = response.getWriter();
out.println("<h1><b>WELCOME "+name+"</b></h1>");
}
}
ANSWER:
• Request Dispatching can be used to include or forward contents to another servlet or a JSP.
• Request Dispatching is a technique that allows a Servlet or a JSP page to dispatch a request
to another Servlet or a JSP page or a HTML page, which will be responsible for any further
processing that generates the response.
• RequestDispatcher interface is defined in package – javax.servlet package.
• RequestDispatcher interface has two methods:
o include()
o forward()
• Both the methods allow delegating the request-response processing to another resource, after
the calling servlet has finished any preliminary processing.
ADITI CHIKHALIKAR 3
Pointer include method forward method
Definition include() allows including the content
forward() allows forwarding the request to another
produced by another resource such as Servlet, JSP or an HTML file on the server. This
Servlet, JSP or an HTML file in the calling
resource then takes over the responsibility for
Servlet’s response. producing the response.
Example To include the response of one Servlet into
To forward the client request to another servlet.
another. forward() is useful when one Servlet does some
preliminary processing of a request and wants to let
another servlet/jsp complete the generation of
response.
Syntax public void include(ServletRequest public void forward(ServletRequest request,
request, ServletResponse response) throws ServletResponse response) throws
ServletException, IOException ServletException, IOException
Code Example RequestDispatcher RequestDispatcher
rd=request.getRequestDispatcher(“index. rd=request.getRequestDispatcher(“WelcomeServl
html"); et");
//index.html is a html file. //WelcomeServlet is the name of the servlet
rd.include(request, response); rd.forward(request, response);
ADITI CHIKHALIKAR 4
In diagram servlet 1 is calling servlet, In diagram servlet 1 is calling servlet, targeted
targeted servlet is servlet 2 servlet is servlet 2
4. Program: 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. U
import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
ADITI CHIKHALIKAR 5
5. Define Request Dispatcher interface. List its two methods with Code Snippet. U
• Request Dispatching can be used to include or forward contents to another servlet or a JSP.
• Request Dispatching is a technique that allows a Servlet or a JSP page to dispatch a request
to another Servlet or a JSP page or a HTML page, which will be responsible for any further
processing that generates the response.
• RequestDispatcher interface is defined in package – javax.servlet package.
• RequestDispatcher Interface:
o Used for dispatching a request.
o Defines an object, which receives request from a visitor’s browser and sends these
requests to any other resource such as Servlet, HTML file, or JSP on the web server.
o Servlet Engine creates the RequestDispatcher object, which is used as a wrapper around
a web server located through the path specified or given by a particular name.
• Write some points about 2 methods: include and forward. Take from table in question
3
Code:
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
String uname=request.getParameter("txtUname");
String pass=request.getParameter("txtPwd");
if(pass.equals("servlet"))
{
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else
{
out.println("<h1>Login failed!! Try again</h1>");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
}
ADITI CHIKHALIKAR 6
Chapter 8
6. What is cookie? Explain the need of the creation of the same. OR Explain the use of
cookies? Why do we need cookies? U
ANSWER:
➢ Cookies are small text files that are created by a server-side program such as Servlet run
at the Web server.
➢ Many websites use small strings of text known as cookies to store persistent client-side
state between connections.
➢ Cookies are passed from server to client and back again in the HTTP headers of requests
and responses.
➢ Cookies can be used by a server to indicate session IDs, shopping cart contents, login
credentials, user preferences, and more.
➢ Disadvantages: It will not work if cookies are disabled in the browser. Only textual
information can be set in the Cookie object.
➢ A Cookie contains more than simply a name and a value. In fact, it has 6 parameters
that can be passed to it:
⎯ Name of the cookie – fbvisit, fbusername
⎯ Value of the cookie – 21, Aditi
⎯ Expiration date of the cookie – 1 week
⎯ Path the cookie is valid for – C:\Temp
⎯ Domain the cookie is valid for – facebook.com
⎯ Need for a secure connection to exist to use the cookie -HTTPS
ADITI CHIKHALIKAR 7
➢ Cookies can live on user’s computer until the developer that created the cookie
programmatically decides it’s been long enough and they automatically die[.i.e.expire].
➢ It is because of this program controlled cookie lifespan that cookies are fabulous for
storing information such as a visitor’s username, password or language preferences.
7. What is a Cookie? [WRITE FROM ABOVE QUESTION] Explain its types. OR Define
cookie. [WRITE FROM ABOVE QUESTION] What are its Kinds? OR What are
different kinds of Cookie? OR How many types of Cookies are there in Servlet? Where
are they Used? OR Differentiate between persistent and session cookies. U
ANSWER:
Kinds/ Types of Cookies:
❑ Permanent/Persistent Cookies
➢ Cookies that are stored on a user’s computer and are not deleted when the browser is
closed.
➢ Can retain user preferences for a particular website, allowing these preferences to be
used in all future browsing sessions.
➢ Can be used to identify individual users, so that website can analyse user’s surfing
behaviour within the website.
➢ Cookies can also be used to provide site information such as the number of visitors, the
average time spent on a particular page and performance of the website.
➢ Usually configured to keep track of users for a prolonged period of time.
➢ Can be used for advertisement targeting and user profiling.
➢ Typically used by analytics tools (e.g., Google Analytics).
❑ Session/Transient Cookies
➢ Cookies that are stored in the computer’s memory only during a user’s browsing
session and are automatically deleted from the user’s computer when the Web browser
is closed.
➢ These cookies usually store a session ID that is not permanently bound to the user,
allowing the user to move from page to page without having to login repeatedly.
➢ Widely used by commercial websites[for eg: to keep track of items that a consumer has
added to a shopping cart.]
➢ Session cookies are never written on the hard drive and they do not collect any
information from the user’s computer.
➢ Expire at the end of the user’s browser session. They also become no longer accessible
after the session has been inactive for a specified length of time.
➢ Lightweight and automatically garbage-collected.
➢ Cannot be shared across different browser tabs unless explicitly coded for it.
➢ Often used with HTTPS for secure data exchange.
ADITI CHIKHALIKAR 8
❑ Creating A Cookie Constructor
➢ To create a cookie, Cookie() constructor is used. The following information must be
passed to Cookie() when attempting to create a cookie:
➢ Cookie name [this is mandatory]
➢ Value of the cookie [Example: username]
➢ Syntax:
public Cookie(String <name>, String <value>);
Here, a new cookie is created with an initial name and value.
❑ Setting a Cookie
➢ To set a cookie, call the Cookie constructor by passing it a cookie name and a cookie
value, where name and value are strings:
Cookie ck1 = new Cookie(“username”, “it”);
➢ Servlets that wish to set cookies must add their cookie to the response sent back to the
browser.
❑ Reading a Cookie
➢ When a client sends a request, all cookies are sent as part of the request.
➢ The servlet can access these cookies via:
Cookie[] ck = request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.println("<h1>"+ck[i].getName()+ " : "+ck[i].getValue()+"</h1>");
}
➢ request.getCookies(): Returns array of all the cookies
➢ ck[i].getName(): Returns the name of existing cookie.
➢ ck[i].getValue(): Returns the value of existing cookie.
❑ Expiration of a Cookie
➢ If the cookie holds user identification that facilitates access to sensitive data or allow
changes to be made, for eg: a web based email service then cookies should expire after a
small period of time.
❑ The following is the syntax that allows specifying the expiration time and belongs to the
class javax.servlet.http.Cookie:
ck1.setMaxAge(int secondsvalue)
➢ 0 means cookie is deleted immediately (not stored); -1 means cookie is deleted after
browser is closed.
ADITI CHIKHALIKAR 9
❑ Destroying of a Cookie
➢ When developing a website, there are situations that require erasing a cookie that was
created. Often this is because the cookie is no longer needed.
➢ The following are the steps that help destroy an already existing cookie:
⎯ Set the cookie’s value to null.
⎯ Set the maximum age of cookie to zero
ck1 = new Cookie("username", null);
ck1.setMaxAge(0); // Delete immediately
response.addCookie(ck1);
9. Explain the methods of cookie class that facilitate the creation, manipulation and
deletion of the cookies. U
ANSWER:
Rest all parts covered in question above.
-- Manipulation of the cookie:
➢ Use the cookie constructor, keep the name same and change the value
ck1 = new Cookie("username”, “TY IT");
10. Explain Cookie class with its constructor and any ten/10 methods.
OR
Explain in brief creation of cookie.
OR
List and explain methods of cookies class and explain use of cookies?
OR
Where are a cookies used? Describe any four important methods of cookie class.
OR
List and explain important methods of cookie in java servlet?
OR
Define following methods of Cookie Class: [getMaxAge(), getSecure(), getValue(),
getDomain(), setPath()]
OR
Explain Cookie class with its constructor and any five methods. U
ANSWER:
https://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
-- Methods of Cookies:
Cookie class:
public class Cookie
• Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved
by the browser, and later sent back to the server.
• 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.
• The name of a cookie cannot be changed once the cookie has been created.
• The value can be anything the server chooses to send.
Constructor
• Cookie(String name, String value)
• Constructs a cookie with the specified name and value.
ADITI CHIKHALIKAR 10
• Cookie ck1 = new Cookie("username”, “it");
Cookies Methods:
1. public void setComment(String purpose): Specifies a comment that describes a cookie's
purpose. The comment is useful if the browser presents the cookie to the user. Parameters:
purpose - a String specifying the comment to display to the user
2. public String getComment(): Returns the comment describing the purpose of this cookie, or
null if the cookie has no comment.
3. public void setDomain(String domain): Specifies the domain within which this cookie should
be presented. A domain name begins with a dot (.foo.com) and means that the cookie is
visible to servers in a specified Domain Name System (DNS) zone (for example,
www.foo.com, but not a.b.foo.com). By default, cookies are only returned to the server that
sent them. Parameters: domain - the domain name within which this cookie is visible;
4. public void setMaxAge(int expiry): Sets the maximum age in seconds for this Cookie. The
value is the maximum age when the cookie will expire, not the cookie's current age.
Parameters: expiry - an integer specifying the maximum age of the cookie in seconds; if
negative, means the cookie is not stored persistently and will be deleted when the Web
browser exits; if zero, deletes the cookie.
5. public void setPath(String uri): Specifies a path for the cookie to which the client should
return the cookie. The cookie is visible to all the pages in the directory you specify, and all
the pages in that directory's subdirectories. A cookie's path must include the servlet that set
the cookie, for example, /catalog, which makes the cookie visible to all directories on the
server under /catalog. Parameters: uri - a String specifying a path
6. public String getPath(): Returns the path on the server to which the browser returns this
cookie. The cookie is visible to all subpaths on the server. for example, /catalog
7. public void setSecure(boolean flag): Indicates to the browser whether the cookie should only
be sent using a secure protocol, such as HTTPS or SSL. The default value is false.
Parameters: flag - if true, sends the cookie from the browser to the server only when using a
secure protocol; if false, sent on any protocol
8. public boolean getSecure(): Returns true if the browser is sending cookies only over a secure
protocol, or false if the browser can send cookies using any protocol.
9. public void setValue(String newValue): Assigns a new value to this Cookie. Parameters:
newValue - the new value of the cookie. With Version 0 cookies, values should not contain
white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question
marks, at signs, colons, and semicolons. Empty values may not behave the same way on all
browsers.
10. public String getValue(): Gets the current value of this Cookie.
11. public int getVersion(): Returns the version of the protocol this cookie complies with.
Cookies provided by a browser use and identify the browser's cookie version.
12. public void setVersion(int v): Sets the version of the cookie protocol that this Cookie
complies with. Parameters: v - 0 if the cookie should comply with the original Netscape
specification; 1 if the cookie should comply with RFC 2109
13. public Object clone(): Overrides the standard java.lang.Object.clone method to return a copy
of this Cookie.
14. public void setHttpOnly(boolean isHttpOnly): Marks or unmarks this Cookie as HttpOnly.
If isHttpOnly is set to true, this cookie is marked as HttpOnly, by adding the HttpOnly
attribute to it. HttpOnly cookies are not supposed to be exposed to client-side scripting code,
and may therefore help mitigate certain kinds of cross-site scripting attacks. Parameters:
isHttpOnly - true if this cookie is to be marked as HttpOnly, false otherwise
15. public boolean isHttpOnly(): Checks whether this Cookie has been marked as HttpOnly.
Returns true if this Cookie has been marked as HttpOnly, false otherwise
ADITI CHIKHALIKAR 11
Chapter 9
11. Explain how java handles session management of a servlet application through
HTTPSession. U
ANSWER:
HttpSession interface
In such case, container creates a session id for each user.The container uses this id to identify the
particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
ADITI CHIKHALIKAR 12
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
12. Write a servlet program to create a session and display the following: U
i) Session ID ii) New or Old iii) Creation Time
ANSWER:
import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
PrintWriter pw = request.getWriter();
HttpSession hs = request.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()));
}
}
ADITI CHIKHALIKAR 13
➢ Sessions provide a virtual connection between the client and the server, making it
possible to recognize returning users within the same interaction window.
➢ A session occurs between the time that a client logs in to the desktop environment and
the time that the client logs out.
➢ The session manager [a module of Java Servlet] automatically starts after the Login
Manager authenticates the client.
➢ For example, a client can save the state of a session and return to that session the next
time the client logs in.
➢ During a visit to an Internet shopping site, a session could be the series of transactions
that a client makes while adding items to a shopping cart.
➢ The session may consist of multiple requests to the same resource to many different
resources on the same website.
➢ A session is the amount of time which a client takes while navigating through a website.
➢ To establish a persistent virtual connection between the client and the Web server. Such
a virtual connection associates each request received by the Web server with the client
that issued it. This association is accomplished as follows:
➢ ❑ The visitor's web browser returns a piece of state information with each new request.
➢ ❑ The Web server uses this piece of information, which is usually called a SESSION
ID uniquely identify the visitor's Web browser.
➢ ❑ The Web server associates the current request with the client's previous requests.
➢ ❑ The Web server can thus identify the visitors using such virtual connections.
➢ These virtual connections are commonly referred to as sessions. Sessions are used to
maintain state and a visitor's identity across multiple requests.
Type Description
Server-Side Data is stored on the web server. Only the Session ID is sent to the client.
Session This is secure and commonly used.
Cookieless Session ID is passed via the URL or hidden fields instead of cookies.
Session Used when clients have cookies disabled.
Persistent A session that lasts beyond a single browser session, e.g., through a
Session “Remember Me” feature. Data persists for days/weeks.
Non-Persistent Ends when the browser is closed or after a fixed timeout. Most common
Session session type for security-sensitive applications.
14. Explain various steps comprising life cycle of HttpSession. OR Explain lifecycle of Http
Session? U
ANSWER:
ADITI CHIKHALIKAR 14
1. Visitor makes a request for a resource from the web server.
2. Web Server delivers authentication module that results in the visitor’s web browser
displaying a login form.
3. Visitor keys in username and password, returned to the web server.
4. Web server returns a valid Session ID that allows this visitor to be uniquely identified.
This begins HTTP session.
1. Visitor’s web browser issues any number of request to Web server.
2. The visitor closes the browser without explicitly logging out.
3. After 30 minutes, web server expires the session by deleting the SESSION ID.
This concludes the HTTP SESSION.
15. What is session tracking? What are the ways to track the session? OR What are
sessions? Elaborate different methods of Session Tracking. OR What are sessions?
Which methods are used in tracking a session? U
ANSWER:
➢ The Servlet API's, HttpSession, provides developers all that is required to track sessions
using Servlet code spec. Each user that invokes the Servlet is mapped to a specific
session, represented by an HttpSession instance.
➢ When a browser makes an HTTP request, a SESSION IDentifier is delivered by the
HttpSession instance and delivered to the Servlet.
➢ The next time the browser connects to the Web server and returns the SESSION
IDentifier stored within the cookie, the Web server understands that it is working with
the continuation of an earlier session.
➢ With session tracking, the SESSION ID is the only state data that is maintained between
HTTP requests between the Web server and a browser.
➢ Servlet API provides javax.servlet.http.HttpSession through which session handling is
implemented in Java EE, server side programming. Developers craft Servlet code to store
the SESSION ID on a client using a cookie, which is the default mechanism or by
rewriting the URL and appending the SESSION ID to each link that the client uses.
➢ Methods of Session Tracking:
➢ 1. Cookies
➢ Store state information on a visitor’s hard disk.
➢ Some websites chose to use an alternate management mechanism, for state and session
management.
➢ Visitor specific information is stored in a database table at Web server rather than in a
cookie on the visitor’s computer. This simplifies the communication with the visitor’s
browser.
➢ 2. URLs Rewriting
➢ With URL rewriting approach, the client appends some additional data to the end of
each URL, which identifies the session and the Web server associates that identifier with
data it has stored about that session. In other words, URL rewriting stores session
details as part of the URL itself.
➢ For example, consider the following link in a Web page:
➢ <a href="/bookshop/logincheck">
➢ which can be rewritten as:
➢ <a href =“/bookshop/logincheck; jsessionid=KD327888GMP444"›
➢ 3. Hidden Variables:
➢ Using a hidden form field implements anonymous session tracking between the visitor
and the Web server. For this process to work successfully the hidden form field and the
data held within it must always be exchanged between the client and the Web server.
ADITI CHIKHALIKAR 15
➢ Thus, there is a tightly coupled dependency between client browser and Web server
involving hidden fields to track a user session bound to a series of dynamically generated
web pages.
➢
➢ 4. Secure Socket Layer[SSL]
➢ Sits between application-level protocol[HTTP] and low level protocol[eg: TCP/IP]. SSL
works in the following manner:
➢ A user connects to the secure site using the HTTPS [HTTP plus SSL] protocol.
➢ The server signs its public key with its private key and sends it back to browser.
➢ The browser uses server's public key to verify that the same visitor who signed the key
actually owns it.
➢ The browser checks to see whether a trusted certificate authority signed the key. If not,
then the browser asks the user if the key can be trusted and proceeds as directed.
➢ The client generates a symmetric [DES] key for session, which is encrypted with the
server's public key and sent back to the server. This new key is used to encrypt all the
subsequent transactions. The symmetric key is used because of high computational cost
of public key cryptosystems.
➢ All this is completely transparent to Servlets and Servlet developers. Just obtain an
appropriate server certificate, install it and configure the server appropriately.
Information transferred between Servlets and clients is now encrypted.
16. Explain URL Rewriting and Hidden Variable as a means of dealing with sessions. U
➢ Encode URLs in session Servlet:
➢ URLs can be encoded either for returning URL or redirecting them. encodeURL() and
encodeRedirectURL() are part of HttpServletResponse. Use encodeURL() to make the
Servlet return the URLs to the browser or encodeRedirectURL() to redirect them to a
specific URL.
➢ The following example demonstrates rewriting URLs to return to the browser where a
Servlet is considered to have the following link:
out.println("<a href=‘/bookshop/logincheck’>catalog<a>");
Modify the Servlet to call encodeURL() before sending the URL to the output stream:
out.println("<a href=’");
out.println(response.encodeURL("/bookshop/logincheck/"));
out.println("'>catalog</a>"),
The following example demonstrates rewriting URLs to return to sendRedirect():
response.sendRedirect("http://losthost:8080/bookshop/logincheck");
➢ Modify the Servlet to call encodeRedirectURL() before sending the URL to the output
stream:
response.sendRedirect(response.encodeRedirectURL("http://losthost:8080/bookshop/loginc
heck"));
2. Creating an entry point to the application using Servlet or JSP (GUI)
3. Avoid using plain HTML files in the application(Session state by Java)
ADITI CHIKHALIKAR 16
➢ Hidden Variables:
➢ Using a hidden form field implements anonymous session tracking between the visitor
and the Web server. For this process to work successfully the hidden form field and the
data held within it must always be exchanged between the client and the Web server.
➢ Thus, there is a tightly coupled dependency between client browser and Web server
involving hidden fields to track a user session bound to a series of dynamically generated
web pages.
ADITI CHIKHALIKAR 17
• Session Identifier in Each Request:
Every HTTP request should carry a unique Session ID (via cookies, URL rewriting,
or hidden fields) to associate the request with the correct session.
• Secure Session Token:
Use a cryptographically secure and unpredictable session ID generated by a
trusted web framework to prevent session prediction and hijacking.
• Session Confidentiality:
Ensure that the session ID remains confidential using secure transmission methods
like HTTPS and secure cookies.
• Session Timeout:
Set a timeout for session inactivity to automatically terminate stale sessions and
reduce the risk of misuse.
• Transaction Awareness:
Maintain consistency and integrity by making the session aware of ongoing
transactions during multi-step processes.
• Use Secure Frameworks:
Always use modern and secure web frameworks that offer built-in session
management and protection mechanisms
❑ There are three characteristics that must be followed while managing sessions over the
Web:
➢ State Preservation: Must store important data (e.g., cart items, credentials). Information
must be maintained across multiple HTTP requests.
➢ Session Identification: Each request must include a Session ID to associate with stored
state.
➢ Session Expiry: Session must automatically expire after a period of inactivity.
Otherwise, if a client leaves the website, there is no way the Web server can determine
when the session ended.
18. Write a note on creation and invalidation of sessions. OR Explain how java handles
session management of a servlet application through HTTPSession. U
ANSWER:
❑ A Session involves:
✓ Looking up the session object associated with the current request.
✓ Creating a new session object when necessary
✓ Looking up the information associated with a session
✓ Storing information in a session object
✓ Discarding completed or abandoned sessions
❑ Creating A Session
➢ Every client of a site is associated with javax.servlet.http.HttpSession that Servlets can
use to store or retrieve information about that client.
➢ Syntax:
HttpSession hs = request.getSession(true);
The above code retrieves the current HttpSession for the client or creates one if it does not
exist.
➢ If the Boolean value of getSession() is false, then no session will be created in case there
is no session in existence.
➢ HttpSession hs = request.getSession(true);
➢ The session named hs is created, considering there is no session in existence.
ADITI CHIKHALIKAR 18
➢ In case a session is available, then the existing session is made available.
if(hs.isNew())
out.println(“This is the first time you are visiting this page,");
else
out.println(“Welcome back to this page”) ;
➢ To determine if a session was created using a cookie or is based on URL rewriting.
HttpRequestServlet object request can be used:
if(request.isRequestSessionIdFromCookie())
out.printin("<p>This Session is created from cookie");
if(request.isRequestSessionIdFromURL())
out.println("<p>This Session came as part of the URL"),
❑ Destroying the session
➢ If a website requires a visitor to login and logout to access its resources, then whenever
a visitor logs out, just invalidate the session by calling invalidate() of the HttpSession
object.
➢ hs.invalidate();
ADITI CHIKHALIKAR 19
20. List and explain methods used with sessions. U
ANSWER:
• HttpSession interface 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
o View and manipulate information about a session, such as the session identifier,
creation time, and last accessed time
o Bind objects to sessions, allowing user information to persist across multiple user
connections
Methods:
1. long getCreationTime() - Returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
2. String getId() - Returns a string containing the unique identifier assigned to this session. The
identifier is assigned by the servlet container and is implementation dependent.
3. long getLastAccessedTime() - Returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the
time the container received the request. Actions that your application takes, such as getting or
setting a value associated with the session, do not affect the access time.
4. ServletContext getServletContext() - Returns the ServletContext to which this session belongs.
5. void setMaxInactiveInterval(int interval) - Specifies the time, in seconds, between client requests
before the servlet container will invalidate this session. An interval value of zero or less indicates
that the session should never timeout. eg: hs.setMaxInactiveInterval(60*60*24);
6. int getMaxInactiveInterval() - Returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses. After this interval, the servlet
container will invalidate the session. The maximum time interval can be set with the
setMaxInactiveInterval method. A return value of zero or less indicates that the session will
never timeout.
7. HttpSessionContext getSessionContext(): Returns the object of HttpSessionContext.
8. Object getAttribute(String name) - Returns the object bound with the specified name in this session,
or null if no object is bound under the name. Parameters: name - a string specifying the name of
the object
9. Object getValue(String name) - Parameters: name - a string specifying the name of the object.
Returns: the object with the specified name. [OLD – Replaced by getAttribute()]
10. Enumeration<String> getAttributeNames() - Returns an Enumeration of String objects containing
the names of all the objects bound to this session.
11. void setAttribute(String name, Object value) - Binds an object to this session, using the name
specified. If an object of the same name is already bound to the session, the object is replaced.
Parameters are name of attribute and its value. name - the name to which the object is bound;
cannot be null, value - the object to be bound.
12. void removeAttribute(String name) - Removes the object bound with the specified name from this
session. If the session does not have an object bound with the specified name, this method does
nothing. Parameters: name - the name of the object to remove from this session
13. void invalidate() :Invalidates this session then unbinds any objects bound to it.
ADITI CHIKHALIKAR 20
14. boolean isNew() : Returns true if the client does not yet know about the session or if the client
chooses not to join the session. For example, if the server used only cookie-based sessions, and the
client had disabled the use of cookies, then a session would be new on each request. Returns: true
if the server has created a session, but the client has not yet joined
ADITI CHIKHALIKAR 21
Chapter 10
22. Explain the working of Non-Blocking I/O. OR Write a note on nonblocking I/O. OR
Provide overview of non-blocking I/O and its characteristics. U
ANSWER:
• Non blocking IO does not wait for the data to be read or write before returning. Java NIO
non- blocking mode allows the thread to request writing data to a channel, but not wait
for it to be fully written. The thread is allowed to go on and do something else in a mean
time.
• java NIO is buffer oriented I/O approach. Data is read into a buffer from which it is
further processed using a channel. In NIO we deal with the channel and buffer for I/O
operation.
• The major difference between a channel and a stream is:
• o A stream can be used for one-way data transfer. V/s o A channel provides a two-way
data transfer facility.
• Therefore with the introduction of channel in java NIO, the non-blocking I/O operation
can be performed.
• Channels : In Java NIO, the channel is a medium that transports the data efficiently
between the entity and byte buffers. It reads the data from an entity and places it inside
buffer blocks for consumption.
• Non-blocking I/O operations allow a single process to serve multiple requests at the same
time. Instead of the process being blocked and waiting for I/O operations to complete,
the I/O operations are delegated to the system, so that the process can execute the next
piece of code.
• 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.
• Blocking also makes your server vulnerable to thread starvation. Consider a server with
200 threads in its thread pool. If 200 requests for large content are received from slow
clients, then the entire server thread pool may be consumed by threads blocking to write
content to those slow clients. Asynchronous IO allows the threads to be reused to handle
other requests while the slow clients are handled with minimal resources.
• How it works?
• The basic flow for a servlet that calls an external REST service using an async HTTP
client (for example AsyncHttpClient) looks like this:
• First of all the servlet where we want to provide async support should have
@WebServlet annotation with asyncSupported value as true.
• 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.
• 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.
• 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
ADITI CHIKHALIKAR 22
processing is finished, we should call AsyncContext.complete( ) method to let
container know that async processing is finished.
• If incoming data is blocking or streamed slower than the server can read then the server
thread waits for that data. Same can happen if data is written in ServletOutputStream.
• Ex: Web containers in application servers use a server thread per client request.
• Containers need a large amount of threads to serve all the client requests.
• Scalability limitations include running out of memory or exhausting the pool of container
threads.
• Asynchronous processing refers to assigning these blocking operations to a new thread
and returning the thread associated with the request immediately to the container.
• To create scalable web applications, the developer must ensure that no threads associated
with a request can be sitting idle:
▪ Thread needs to wait for a resource to become available or process data
before building the response.
▪ Thread needs to wait for an event before generating the response.
• Servlet 3.1 provides non-blocking I/O technology for servlets and filters when processing
request in asynchronous mode, by adding the two interfaces, ReadListener and
WriteListener.
• Non-blocking I/O can be performed using the following steps:
• 1. The request is put into the asynchronous mode.
• 2. An input stream and/or output stream is retrieved from the request and response objects
created in the service method.
• 3. A listener is assigned, that is ReadListener to the input stream and/or WriteListener
to the output stream retrieved.
• 4. The request and the response is processed within the listener’s callback methods.
ADITI CHIKHALIKAR 23
24. What is Non-Blocking I/O? Explain WriteListener and ReadListener performing in
Non- Blocking I/O? U
ANSWER:
To use the new non-blocking I/O technology, implement either of the following interface in
the application:
1. ReadListener Interface:
When performing non-blocking reads. This interface is registered to a
ServletInputStream so that reads can be performed when the listener finds that the servlet
content and be read without blocking.
2. WriteListener Interface:
When performing non-blocking writes. This interface is registered to a
ServletOutputStream so that writes can be performed when the listener finds that
servlet content and be written without blocking.
25. Explain using a code snippet the onDataAvailable() and onAllDataRead() methods of
ReadListener interface. U
ANSWER: Refer Book and Answer given above.
ADITI CHIKHALIKAR 24
ADITI CHIKHALIKAR 25
ADITI CHIKHALIKAR 26
Chapter 11
26. Write a short note on Uploading file with java Servlet? OR Which points are important
while uploading a file? OR Explain about the file uploading feature of a servlet. OR
Which things needs to be carefully checked and understood while writing file uploading
code in servlet? OR Explain the following w. r. t. working with files in Servlet. U
i) @MultipartConfigure, ii) fileSizeThreshold, iii) location, iv) maxFileSize, v)
maxRequestSize U
ANSWER:
➢ Developers no longer have to depend on any external library, since Java EE 6 provides a
built-in file upload API.
➢ Servlet 3.0 onwards 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 HttpServletRequest.
➢ javax.servlet.annotation.MultipartConfig is used to indicate that the servlet on which it
is declared expect requests to made using the multipart/form-data MIME type. [MIME
(Multipurpose Internet Mail Extensions) is an extension of the original Simple Mail
Transport Protocol (SMTP) email protocol. It lets users exchange different kinds of data
files, including audio, video, images and application programs, over email.]
➢ @MultipartConfig
➢ To handle multipart/form-data requests which contain file upload data
➢ Servlets annotated with @MultipartConfig may retrieve the Part components of a
given multipart/form-data request by calling getPart() or getParts().
➢ @MultipartConfig annotation support the following optional attributes:
➢ fileSizeThreshold
➢ Holds file size in bytes after which file will be temporarily store on disk. Default
size is 0 bytes.
➢ location
➢ Holds absolute path to a directory on the file system. Default location is “”.
➢ maxFileSize
➢ Holds maximum size allowed for uploaded files, in bytes. Default size is
unlimited.
➢ maxRequestSize
➢ Holds maximum size allowed for mutipart/form-data request, in bytes. Default
size is unlimited.
➢ A Servlet can be used with an HTML form tag to allow users to upload files to the server.
An uploaded file could be a text file or image file or any document.
➢ Creating a File Upload Form
➢ The following HTM code below creates an uploader form. Following are the important
points to be noted down −
• The form method attribute should be set to POSTmethod and GET method can
not be used
• The form enctype attribute should be set to multipart/form-data.
• The form action attribute should be set to a servlet file which would handle file
uploading at backend server. Following example is using UploadServlet servlet
to upload file.
• To upload a single file you should use a single <input .../> tag with attribute
type="file". To allow multiple files uploading, include more than one input tags
with different values for the name attribute. The browser associates a Browse
button with each of them.
ADITI CHIKHALIKAR 27
➢ Write the code snippet in question 20.
1. DiskFileItemFactory is default Factory class for FileItem. When Apache commons read
multipart content and generates FileItem, this implementation keep file content either in memory
or in disk as temporary file, depending upon threshold size. By default DiskFileItemFactory has
threshold size of 10KB and generates temporary files in temp directory, returned by
System.getProperty(“java.io.tmpdir”). Both of these values are configurable. You may get
permission issues if user account used for running Server doesn’t have sufficient permission to
write files into temp directory.
2. Choose threshold size carefully based upon memory usage, keeping large content in memory
may result in java.lang.OutOfMemory exception, while having too small values may result in
lots of temporary files.
3. Apache commons file upload also provides FileCleaningTracker to delete temporary files
created by DiskFileItemFactory. The FileCleaningTracker deletes temporary files as soon as
corresponding File instance is garbage collected. It accomplish this by a cleaner thread which is
created when FileCleaner is loaded. If you use this feature, than remember to terminate this
Thread when your web application ends.
4. Keep configurable details e.g. upload directory, maximum file size, threshold size etc. in
config files and use reasonable default values in case they are not configured.
5. It’s good to validate size, type and other details of Files based upon your project requirement
e.g. you may want to allow upload only images of certain size and certain types e.g. JPEG, PNG
etc.
28. Write a program to create to servlet application to upload a file. OR Write a program
using Servlet application to upload a file. OR Write a program to upload file using
servlet. U
ANSWER:
ADITI CHIKHALIKAR 28
Refer Practical for program.
29. Write a program to create to servlet application to download a file. OR Write a servlet
code to download file. U
ANSWER:
Refer Practical for program.
ADITI CHIKHALIKAR 29
ADITI CHIKHALIKAR 30