EJ Unit 2
EJ Unit 2
EJ Unit 2
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.
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
RequestDispatcher Application:
index.html
<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.
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
{
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 {
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)
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.
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);
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
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.
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.
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);
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");
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
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
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");
}
out.println("<html><body bgcolor="+bcolor+"> <font color="+ fcolor +"> Color servlet
</font> </body></html>");
}
}
https://www.youtube.com/watch?v=5tLGwdyPGRY
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.
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
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);}
}
}
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);
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:
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.
Stream oriented
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)
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;
}
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.*;
bw.write("Reading completed...");
bw.flush();
bw.close();
}
}
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.
A - session.invalidate()
B - response.deleteSession()
C - request.deleteSession()
2. Which class provides stream to read binary data such as image etc. from the request
object?
a. ServltInputStream
c. Both A & B
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
a. Genereic Servlets
b. HttpServlets
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
a. True
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
a. javax.servlet
b. javax.servlet.http
c. Both A & B
b. For each request, it starts a process and Web server is limited to start processes
Answers
1 – a, 2 – a, 3 – a, 4 – b, 5 – b, 6 – b, 7 – b, 8 - a
9 – c, 10 – d, 11 - d