EJ Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Enterprise

Java
MODULE 2: RequestDispatcher, Cookies, Session, Working
with Files, Working with Non-Blocking I/O

Vidyalankar School of
Information Technology
Wadala (E), Mumbai
www.vsit.edu.in

Beena Kapadia
Certificate
This is to certify that the e-book titled “Enterprise Java” comprises
all elementary learning tools for a better understating of the
relevant concepts. This e-book is comprehensively compiled as per
the predefined parameters and guidelines.

Signature Date: 08-07-2019


Ms. Beena Kapadia
Assistant Professor
Department of IT
DISCLAIMER: The information contained in this e-book is compiled and distributed
for educational purposes only. This e-book has been designed to help learners
understand relevant concepts with a more dynamic interface. The compiler of this e-
book and Vidyalankar Institute of Technology give full and due credit to the authors of
the contents, developers and all websites from wherever information has been sourced.
We acknowledge our gratitude towards the websites YouTube, Wikipedia, and Google
search engine. No commercial benefits are being drawn from this project.

Compiled by Beena Kapadia


Unit II RequestDispatcher, Cookies, Session, Working with Files, Working with Non-
Blocking I/O

Request Dispatcher: RequestDispatcher Interface, Methods of RequestDispatcher,


RequestDispatcher Application. COOKIES: Kinds Of Cookies, Where Cookies are Used? Creating
Cookies Using Servlet, Dynamically Changing The Colors Of A Page
SESSION: What Are Sessions? Life cycle Of HttpSession, Session Tracking With Servlet API, A
Servlet Session Example
Working With Files: Uploading Files, Creating an Upload File Application, Downloading Files,
Creating a Download File Application.
Working With Non-Blocking I/O: Creating a NonBlocking Read Application, Creating The Web
Application, Creating Java Class, Creating Servlets, Retrieving The File, Creating index.jsp

Recommended Books :
Java EE 7 For Beginners by Sharanam Shah, Vaishali Shah
Java EE 8 Cookbook: Build reliable applications with the most robust and mature technology for
enterprise development by Elder Moraes
Advanced Java Programming by Uttam Kumar Roy

Prerequisites
Unit II Sem I Sem. II Sem. III Sem. IV Sem. V Sem. VI
RequestDispatcher, IP (C) OOPS Python Applets, -- PROJECTS
Cookies, Session, with C++ File On website
Working with Handling designing in
Files, Working in Java – JSP and
with Non-Blocking Core Java Servlets OR
I/O Android
Application

Compiled by Beena Kapadia


RequestDispatcher interface
RequestDispatcher interface defines an object created by Servlet container that receives
request from the client and sends them to any resources such as Servlet, Html, File or
JSP file on the server.

void forward(ServletRequest, ServlerResponse)-Forwards a request from a servlet to


another resource such as Servlet, JSP or HTML file on the server.

void include(ServletRequest, ServlerResponse)- Includes the content of a resource such


as Servlet, JSP, HTML file in the response.

RequestDispatcher Application:
index.html
<body>

Compiled by Beena Kapadia


<form method="get" action="NewServlet1">
user name <input type="text" name="un">
password <input type="password" name="pw">
<br><br>
<input type="submit" value="submit">
</form>
</body>

Servlet1.java
package reqdisp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet1 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String username=req.getParameter("un");
String password=req.getParameter("pw");
req.setAttribute("s1un",username);
req.setAttribute("s1pw", password);
RequestDispatcher rd=req.getRequestDispatcher("NewServlet2");
rd.forward(req, res);
}
}
Servlet2.java
package reqdisp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String s2un=(String)req.getAttribute("s1un");
String s2pw=(String)req.getAttribute("s1pw");
out.print("Username: "+s2un+" password: "+s2pw);
}
}

Another application

Practical 2.a. Using Request Dispatcher Interface create a Servlet which will validate
the password entered by the user, if the user has entered "Servlet" as password, then
he will be forwarded to Welcome Servlet else the user will stay on the index.html page
and an error message will be displayed.

Compiled by Beena Kapadia


• Index.html
<body>
<form method="post" action="ValidateServlet">
User Name: <input type="text" name ="un"><br>
Password: <input type="password" name ="pw"><br>
<input type="submit" value="Login">
</form>
</body>

ValidateServlet.java
package reqdisserapp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ValidateServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)throws
IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String username=req.getParameter("un");
String password=req.getParameter("pw");

if(password.equals("Servlet")) {
req.setAttribute("s1username",username);
req.setAttribute("s1password",password);
RequestDispatcher rd= req.getRequestDispatcher("/WelcomeServlet");
rd.forward(req, res);
}
else {
RequestDispatcher rd= req.getRequestDispatcher("/index.html");
out.print("Incorrect password");
rd.include(req, res);
}
}
}

WelcomeServlet.java
package reqdisserapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet
{

Compiled by Beena Kapadia


public void doPost(HttpServletRequest req, HttpServletResponse res)throws IOException,
ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();

String s2username = (String)req.getAttribute("s1username");


String s2password = (String)req.getAttribute("s2password");
out.println("Welcome "+s2username);
}
}

Basic concept of request dispatcher


The RequestDispatcher interface provides the facility of dispatching the request to another
servlet. This interface can also be used to include the content of another resource also like
html, servlet or jsp.
The client (browser) will not understand that final output is from another servlet, but it will
understand that the output is from the first servlet to whom request is originally made.
e.g. if html sends request to servlet1 and servlet1 dispatches the request to servlet2 and
servlet2 shows the final output but on URL it will show servlet1 only.

Difference between RequestDispatcher interface and sendRedirect() method


SendRedirect() intimates the browser by sending the URL of the content
• it will search the content between the servers. it is slow because it has to intimate the
browser by sending the URL of the content, then browser will create a new request for
the content within the same server or in another one.
URL rewrinting: In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource. We can send parameter name/value pairs using the
following format:
• url?name1=value1&name2=value2&??

index.html
<body>
<form method="get" action="NewServlet1">
user name <input type="text" name="un">
password <input type="password" name="pw">
<br><br>
<input type="submit" value="submit">
</form>
</body>

Servlet1.java
package reqdisp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet1 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

Compiled by Beena Kapadia


res.setContentType("text/html");
PrintWriter out = res.getWriter();
String s1un=req.getParameter("un");
String s1pw=req.getParameter("pw");
res.sendRedirect("NewServlet2?s2un="+s1un+"&s2pw="+s1pw);
}
}

Servlet2.java
package reqdisp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String s2un=(String)req.getParameter("s2un");
String s2pw=(String)req.getParameter("s2pw");
out.print("Username: "+s2un+" password: "+s2pw); }
}

Source : https://www.youtube.com/watch?v=CRvcm7GKrF0&t=46s
(Introduction to Servlets)

Compiled by Beena Kapadia


Session Tracking Techniques:
HTTP is a stateless protocol that provides no way for a server to recognize that a sequence
of request come from the same client. (not even IP Address). Following are various
techniques for session tracking:
1) HTTPSession
2) Cookies
3) URL rewriting
4) Hidden form fields

HttpSession Interface
• HttpSession Interface provides a way across more than one page request or visit to a
website and to store information about that user.
• With the help of the HttpSession interface, a session can be created between an HTTP
client and an HTTP server. This session can persist for a specified time period, across
more than one connection or page request from the user.
• A Servlet obtains an HttpSession object using
HttpSession getSession(boolean) of HttpservetRequest.

Some metods of HttpSession:


• String getId()- Returns a string containing the unique identifier assigned to the session.
• long getCreationTime() Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
• long getLastAccessedTime() Returns the last time the client sent a request associated
with this session.
• int getMaxInactiveInterval()- Returns the maximum time interval, in seconds, that the
Servlet container will keep this session open.
• boolean isNew()- Returns true if the client does not yet know about the session or if the
client chooses not to join the session.
• void setMaxInactiveInterval(int interval)- sets the maximum time interval, in
seconds, that the Servlet container will keep this session open.
A session involves:
• Looking up the session object associated with the current request (check for
availability)
• Creating a new session object when necessary (create new object if required)

Compiled by Beena Kapadia


• Looking up the information associated with a session (browse all pages)
• Storing information in a session object (store the selected data in session object)
• Discarding the object (destroy object)

//session methods - sessionApp.SessionMethodsDemo.java


public class SessionMethodsDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
out.println("Session ID= "+session.getId());
out.println("<br>Session Creation Time"+session.getCreationTime());
out.println("<br>Session Last Action Time= "+ session.getLastAccessedTime());
out.println("<br> Max InActive time Interval"+session.getMaxInactiveInterval());
session.setMaxInactiveInterval(6);
out.println("<br> InActive time Interval" + session.getMaxInactiveInterval());
response.setHeader("Refresh", new
Integer(session.getMaxInactiveInterval()).toString()); }}
}
For session continuity, we can bind the objects on HttpSession instance and get the objects
by using setAttribute and getAttribute methods.

Session example –SessionApp2

Index.html
<body>
<form method=get action="NewServlet1">
user name <input type= "text" name="un">
password <input type= "password" name="pw">
<br><br>
<input type= "submit" value="submit" name="btn">
</form>
</body>

NewServlet1.java
package reqdisp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet1 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String s1un=req.getParameter("un");
String s1pw=req.getParameter("pw");
HttpSession s=req.getSession(true);
s.setAttribute("s1un", s1un);
s.setAttribute("s1pw", s1pw);

Compiled by Beena Kapadia


res.sendRedirect("NewServlet2");
}
}

NewServlet2.java
package reqdisp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession s=req.getSession(true);
String s2un=(String)s.getAttribute("s1un");
String s2pw=(String)s.getAttribute("s1pw");
out.print("Username: "+s2un+" password: "+s2pw);
}
}

Prac2C: To find whether user has visited the page for the first time or how many times user
has visited using session. E.g.VisitSessionApp

Pract2CVisitSessionApp
package visitservlet;
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;
import javax.servlet.http.HttpSession;
public class CalculationVisitServlet extends HttpServlet
{
// private static int counter;
private int counter;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(true);
if(session.isNew())
{
out.print("This is the first time you are visiting this page");
++counter;
}
else

Compiled by Beena Kapadia


{
synchronized(this)
{
if(counter==10)
{
session.invalidate();
counter=0;
request.getSession(false);
}
else
out.print("You have visited this page "+(++counter)+ " times");
}
}
}
}

Providing Continuity with Cookies


• A cookie is basically just a name-value attribute that is issued by the server, stored
on a client machine and returned by the client whenever it is accessing a certain
group of URLs on a specified server.
• Cookie.setMaxAge(long expiry)// in seconds
• HttpServletResponse.addCookie()
• HttpServletRequest.getCookies()

cookie is just a name-value attribute that is issued by the server and stored on a client
machine. It is returned by the client whenever it is accessing a certain group of URLs on a
specified server. Following methods are some methods belongs to Cookie class.

Types of Cookies
The two types of cookies follow:
• Session cookies – Session cookies are stored in memory and are accessible as long as the
user is using the web application. Session cookies are lost when the user exits the web
application. Such cookies are identified by a session ID and are most commonly used to
store details of a shopping cart.
• Permanent cookies – Permanent cookies are used to store long-term information such as
user preferences and user identification information. Permanent cookies are stored in
persistent storage and are not lost when the user exits the application. Permanent
cookies are lost when they expire.

Compiled by Beena Kapadia


Constructor
Cookie(String name, String value): Constructs a cookie with the specified name and value.

Some methods:
a. Cookie.setMaxAge(int expiry): Sets the maximum age in seconds for this Cookie.
b. HttpServletResponse.addCookie():Adds the specified cookie to the response. This
method can be called multiple times to set more than one cookie.
c. HttpServletRequest.getCookies():Returns an array containing all of the Cookie
objects the client sent with this request.

How cookies are created, stored and fetched? Explain with a programming example.
o A cookie is just a name-value attribute that is issued by the server and stored on a
client machine. It is returned by the client whenever it is accessing a certain group
of URLs on a specified server. Following methods are some methods belongs to
Cookie class.
o Cookie.setMaxAge(int expiry): Sets the maximum age in seconds for this Cookie.
o HttpServletResponse.addCookie():Adds the specified cookie to the response. This
method can be called multiple times to set more than one cookie.
o HttpServletRequest.getCookies():Returns an array containing all of the Cookie
objects the client sent with this request.

Following program explains how Cookies are stored and retrieved.


//Store and retrieve Cookie – CookieApp

Index.html

<form action="CookieServlet">
Username: <input type="text" name="un" value="" /><br>
Password: <input type="password" name="pd" value="" />
<input type="submit" value="Submit" />
</form>
CookieServlet.java
public class CookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String un=request.getParameter("un");
String pd=request.getParameter("pd");
Cookie c1=new Cookie("Username",un);
response.addCookie(c1);

Compiled by Beena Kapadia


Cookie c2=new Cookie("Password",pd);
response.addCookie(c2);
response.sendRedirect("Redirect");
}
}
Redirect.java
public class Redirect extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
Cookie[] allCookies=request.getCookies();
String name,val;
for(int i=0;i<allCookies.length;i++)
{
name=allCookies[i].getName();
val=allCookies[i].getValue();
out.println("<br>Name: "+name+" value:"+val);
}
}
}
Another application
To find whether user has visited the page for the first time or how many times user has visited
using Cookie. //Prac2BCookieApp

package cookieapp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet
{
//static int i=1;
private int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");

Compiled by Beena Kapadia


PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("This is the first time you are visiting this page");
}
else
{
synchronized(this)
{
out.println("You visited this page "+i+" times");
}}
i++;
}
}

Uses of Cookies
1. To create a temporary session where the site in some way remembers about what the user was
doing or had chosen between web page requests. It remembers user login and what user has
ordered for online shopping cart.
2. To remember low-security information more permanently
3. To compile user statistics
4. To identify a user during an E-commerce session
5. To avoid keying user name and password to login site

In short cookies are used in:


 Shopping cart application
 Online banking
 Generation of a visitor’s profile
 Fee based services
 Website tracking

GUI Application using Cookie


ForeBackColorApp

Index.html
<form method="get" action="ColorGeneratorServlet">
Background Color
<select name="bc">
<option value="pink"> Pink </option>
<option value="yellow"> Yellow </option>
<option value="aqua"> Aqua </option>
</select>
<br>

Foreground Color

Compiled by Beena Kapadia


<select name="fc">
<option value="red"> Red </option>
<option value="green"> Green </option>
<option value="blue"> Blue </option>
</select>
<br>
<input type="submit" value="Go">
</form>

ColorGeneratorServlet.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ColorGeneratorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String fc=req.getParameter("fc");
String bc=req.getParameter("bc");
Cookie forec=new Cookie("fc",fc);
res.addCookie(forec);
Cookie backc=new Cookie("bc",bc);
res.addCookie(backc);

res.sendRedirect("Redirect");
}
}

Redirect.java

package colorapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Redirect extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");

Compiled by Beena Kapadia


PrintWriter out=res.getWriter();
Cookie[] allCookies=req.getCookies();
String bcolor="white",fcolor="black";
for(int i=0;i<allCookies.length;i++)
{
if(allCookies[i].getName().equals("bc"))
bcolor=allCookies[i].getValue();
if(allCookies[i].getName().equals("fc"))
fcolor=allCookies[i].getValue();

}
out.println("<html><body bgcolor="+bcolor+"> <font color="+ fcolor +"> Color servlet
</font> </body></html>");
}
}

https://www.youtube.com/watch?v=5tLGwdyPGRY

3. Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="city" value="Mumbai">
This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission.

4. URL Rewriting
There is an alternative way to send a cookie: URL Rewriting. The cookie data is appended to the
URL. You should use URL rewriting only as a fallback for browsers that do not support cookies.

Compiled by Beena Kapadia


Working With Files
The steps involved in Uploading files.
Set encodiging type attribute as follows:
enctype attribute of <form> tag
multipart/form-data - No characters are encoded.
text/plain- Spaces are converted to "+" symbols, but no special characters are encoded

type attribute value in <input>tag


type="file"
let the user choose one or more files from their device storage. Once chosen, the files can
be uploaded to a server using form submission
Part getPart()
Retrieve the name, store location, size, and content-type of the file
File name=--------, StoreLocation=--------, size=--------bytes,
isFormField=false, FieldName=filedetails

File getSubmittedFileName()
It returns the selected file name from the FileOpenWindow.

@MultipartConfig
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.
MultipartConfig annotation has following attributes:
• fileSizeThreshold: We can specify the size threshold after which the file will be
written to disk. The size value is in bytes, so 1024*1024*10 is 10 MB.
• location: Directory where files will be stored by default, it’s default value is “”.
• maxFileSize: Maximum size allowed to upload a file, it’s value is provided in bytes.
It’s default value is -1L means unlimited.
• maxRequestSize: Maximum size allowed for multipart/form-data request. Default
value is -1L that means unlimited.
Steps
 Allow browsing the file to upload it
 Allows specifying the location where to upload it
 Display the message indicating a successful file upload
 Display the link to return back to upload more files

File uploading application – FileUploadApp


Index.html
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="filedetails" name="file" >
Destination <input type="text" value="/MyFolder" name="destination">
<br>
<input type="submit" value="Upload file" >
</form>

Compiled by Beena Kapadia


FileUploadServlet.java

package fileservletapp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;

@MultipartConfig
public class FileUploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

String path=req.getParameter("destination");

Part filePart=req.getPart("filedetails");
String sfilePart= filePart.toString();
out.print("<br> filePart: "+sfilePart);
String filename=filePart.getSubmittedFileName().toString();
out.print("<br><br><hr> file name: "+filename);

OutputStream os=null;
InputStream is=null;

try
{
os=new FileOutputStream(new File(path+File.separator+filename));
is=filePart.getInputStream();
int read=0;
byte[] b=new byte[1024];
while ((read = is.read(b)) != -1)
{
os.write(b, 0, read);
}
out.println("<br>file uploaded sucessfully...!!!");
}
catch(FileNotFoundException e){out.print(e);}
}
}

Compiled by Beena Kapadia


response.setContentType(application/OCTET-STREAM) is for all kinds of file.

void setHeader(String name, String value)


setHeader("Content-Disposition" , "attachment; filename=\"" + filename + "\"");
If comment this statement then it will ask you about the editor you want to use to open the
file

Before running the program you need to copy required pdf files in current project’s
webpages folder of netbeans.
File download app – FileDownloadApp

Index.html
<body>
<h1>File Download Application</h1>
Click <a href="DownloadServlet?filename=SampleChapter.pdf">Sample Chapter</a>
<br/><br/>
Click <a href="DownloadServlet?filename=TOC.pdf">Table Of Contents</a>
</body>

DownloadServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("APPLICATION/OCTET-STREAM");
String filename = request.getParameter("filename");
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/" + filename);

Compiled by Beena Kapadia


ServletOutputStream os = response.getOutputStream();
response.setHeader("Content-Disposition","attachment; filename=\"" + filename
+ "\""); // if comment this statement then it wl ask you about the editor with which you
want to open the file
int i;
while ((i=is.read()) != -1) {
os.write();
}
is.close();
os.close();
}
}

Non-Blocking I/O
In Java NIO reading and writing are the fundamental process of I/O.
Reading from channel: We can create a buffer and then ask a
channel to read the data.
Writing to channel: We can create a buffer, fill it with data and ask
a channel to write the data.
The core components used in the reading and writing operation are:
• Channels
• Buffers
• Selectors
Channels and Buffers
• In standard I/O API the character streams and byte streams are
used.
• In NIO we work with channels and buffers. All the I/O in NIO is
started with a channel. Data is always written from a buffer to a
channel and read from a channel to a buffer.
• Data reading operation:
Let's see the channels read data into buffers illustration shown
below:

• Data writing operation:


Let's see the buffers write data into channels illustration shown
below:

Compiled by Beena Kapadia


Selectors
Java NIO provides the concept of "selectors". It is an object that can
be used for monitoring the multiple channels for events like data
arrived, connection opened etc. Therefore single thread can monitor
the multiple channels for data.

Blocking vs. Non-blocking I/O

Blocking I/O
Blocking IO wait for the data to be write or read before returning. Java IO's various streams
are blocking. It means when the thread invoke a write() or read(), then the thread is blocked
until there is some data available for read, or the data is fully written.

Non blocking I/O


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.

Stream oriented

Compiled by Beena Kapadia


Buffer Oriented

steps to execute nonblocking application


1. create an application with name e.g. NonBlockingApplicaion. Create index file as:
<meta http-equiv="Refresh" content="0; URL=NonBlockingServlet">

2. Create Java class named ReadingListener along with package name e.g. nonblkapp. This
class should implement ReadListener to create AsyncContext object, that does the task of
non-blocking (i.e. without waiting) upload or download. This interface has following 3
methods:
a. public void onDataAvailable()
b. public void onAllDataRead() and
c. public void onError(final Throwable t)
WriteListener is used to asynchronize the data. So that without any waiting / blocking it can write.
This interface has following 2 methods:
a. void onWritePossible() and
b. void onError(Throwable t)
ReadingListener has to be created which takes two parameters ServletInputStream to get
the inputstream to read and AsyncContext to get nonblocking feature, as:
ReadingListener(ServletInputStream in, AsyncContext c)

3. Create the Servlet named ReadingNonBlockingServlet. To implement non-blocking I/O,


ReadListener interface should be added to ServletInputStream, as:
ServletInputStream in=request.getInputStream();
in.setReadListener(new ReadingListener(in,ac));

4. Now create NonBlockingServlet. Actual Reading or writing happens in this Servlet. We


take the file name from server and get that resource (file) as stream in InputStream object.
Set URL to the localhost path of ReadingNonBlockingServlet. And typecast that to
HttpURLConnection as we download / upload it is from server.
setChunkedStreamingMode() is used to enable streaming of a HTTP request without
internal buffering, when content length is not known in advanced.

Compiled by Beena Kapadia


https://www.youtube.com/watch?v=wxBcFbzaj9w

prac3c. Create simple Servlet application to demonstrate Non-Blocking Read Operation.

Index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">

<body>
<a href="NonBlockingServlet">Non Blocking Servlet</a>
</body>
</html>

ReadingListener.java
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
public class ReadingListener implements ReadListener
{
ServletInputStream input = null;
AsyncContext ac = null;
ReadingListener(ServletInputStream in, AsyncContext c) {
input = in;
ac = c;
}

Compiled by Beena Kapadia


@Override
public void onDataAvailable()
{
}
public void onAllDataRead()
{
ac.complete();
}
public void onError(Throwable t)
{
ac.complete();
t.printStackTrace();
}
}

ReadingNonBlockingServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Beena Kapadia
*/
@WebServlet (name = "ReadingNonBlockingServlet", urlPatterns =
{"/ReadingNonBlockingServlet"},asyncSupported = true )
public class ReadingNonBlockingServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
AsyncContext ac = request.startAsync();
ServletInputStream in=request.getInputStream();
in.setReadListener(new ReadingListener(in,ac));
}
}
NonBlockingServlet.java
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

Compiled by Beena Kapadia


@WebServlet(name = "NonBlockingServlet", urlPatterns = {"/NonBlockingServlet"})
public class NonBlockingServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String filename = "booklist.txt";
ServletContext c = getServletContext();
InputStream is = c.getResourceAsStream("/"+filename);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

String path = "http://" + request.getServerName() + ":" + request.getServerPort() +


request.getContextPath() + "/ReadingNonBlockingServlet";
out.println("<h1>File Reader</h1>");
//out.flush();
URL url = new URL(path);
HttpURLConnection hc = (HttpURLConnection) url.openConnection();
hc.setChunkedStreamingMode(2); //2bytes at a time
hc.setDoOutput(true); // true if URL connection done
hc.connect();

String text = "";


System.out.println("Reading started...");
BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(hc.getOutputStream()));
while ((text = br.readLine()) != null)
{
bw.write(text);
bw.flush();
out.println(text+"<br>");
out.flush();
try
{
Thread.sleep(1000);
}
catch (Exception ex)
{
out.print(ex);
}
}

bw.write("Reading completed...");
bw.flush();
bw.close();
}
}

Compiled by Beena Kapadia


Assignment Questions
1. Explain RequestDispatcher interface with its method.
2. How cookies are created, stored and fetched? Explain with a programming example.
3. Explain the steps involved in Uploading files.
4. Create a servlet demonstrating the use of session creation and destruction. Also check
whether the user has visited this page first time or has visited earlier also using sessions.
5. Write a Servlet program to dynamically change the foreground and background color of a
page, where color should be selected from HTML file.
6. Explain Cookie with its constructor and methods.
7. What are Sessions? Explain Lifecycle of HTTP session.
8. Explain the steps involved in Downloading files.
9. Using Request Dispatcher Interface create a Servlet which will validate the password
entered by the user, if the user has entered "Servlet" as password, then he will be forwarded
to Welcome Servlet else the user will stay on the index.html page and an error message will
be displayed.
10. Write a program to create a Download File Application.
11. Explain Cookie. Where it is used and what are its types?
12. Short note on Session Tracking with Servlet API
13. Explain the all the classes and interfaces used in working with Non-Blocking I/O.

14. Create a servlet that uses Cookies to store the number of times a user has visited servlet.
15. Write a program to create an Upload File Application.

Multiple Choice Questions:


1. Which of the following code is used to delete a HTTP Session object in servlets?

A - session.invalidate()

B - response.deleteSession()

C - request.deleteSession()

D - None of the above.

2. Which class provides stream to read binary data such as image etc. from the request
object?

a. ServltInputStream

Compiled by Beena Kapadia


b. ServletOutputStream

c. Both A & B

d. None of the above

3. The sendRedirect() method of HttpServletResponse interface can be used to redirect


response to another resource, it may be servlet, jsp or html file.

a. True

b. False

4. Which methods are used to bind the objects on HttpSession instance and get the
objects?

a. setAttribute

b. getAttribute

c. Both A & B

d. None of the above

5. What type of servlets use these methods doGet(), doPost(),doHead, doDelete(),


doTrace()?

a. Genereic Servlets

b. HttpServlets

c. All of the above

d. None of the above

6. Which cookie it is valid for single session only and it is removed each time when
the user closes the browser?

a. Persistent cookie

b. Non-persistent cookie

c. All the above

d. None of the above

7. Web server is used for loading the init() method of servlet.

a. True

Compiled by Beena Kapadia


b. False

8. Which method is used to send the same request and response objects to another
servlet in RequestDispacher ?

a. forward()

b. sendRedirect()

c. Both A & B

d. None of the above

9. Which packages represent interfaces and classes for servlet API?

a. javax.servlet

b. javax.servlet.http

c. Both A & B

d. None of the above

10. What is the lifecycle of a servlet?

a. Servlet class is loaded

b. Servlet instance is created

c. init,Service,destroy method is invoked

d. All mentioned above

11. In the following statements identify the disadvantages of CGI?

a. If number of clients increases, it takes more time for sending response

b. For each request, it starts a process and Web server is limited to start processes

c. It uses platform dependent language e.g. C, C++, perl

d. All mentioned above

Answers

1 – a, 2 – a, 3 – a, 4 – b, 5 – b, 6 – b, 7 – b, 8 - a
9 – c, 10 – d, 11 - d

Compiled by Beena Kapadia

You might also like