Chapter 11. Advanced servlet
ITSS Java Programming Dr. NGUYEN Hong Quang, FITHUT
HttpServletRequest interface
Outline
provide request information for HTTP servlets. The servlet container creates an
HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
HttpServletRequest Interface
Request information
Client request information including :
parameter name and values, and an input stream Attributes : custom information about a request
HttpServletRequest Interface
Operating with attributes
Extends the ServletRequest interface
Returns the value of attribute :
public Object getAttribute(String name)
Stores an attribute in this request :
public void setAttribute(String name, Object o)
Forwarding : cooperation between several Servlets
Client
URL address
Link in a Web page
Application server
Request
Servlet 1
• Require parameters
Web browser
Servlet 2
• Proccessing data
Internet
…
• Connecting to database
Servlet N
• …
Response
Display reading page
Forwarding : methods
public RequestDispatcher getRequestDispatcher
(String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path public void forward (ServletRequest request,
ServletResponse response) Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.
Forwarding : usage example
public void doGet ( HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
// proccessing data
… // Get RequestDispatcher object
RequestDispatcher rd = req.getRequestDispatcher(“/servlet2”);
// forwarding rd.forward(req, res);
}
Application example
inputname_forward.htm
Transmission of information
helloPerson Forward2 Servlet
Setting attributes + Name : input name + Date : access time (new information)
Forward
helloPersonForwar d2 Servlet
Display information
Application example
inputname_forward.htm
Application example
Class HelloPersonForward1 (1)
public class HelloPersonForward1 extends HttpServlet {
// Taking out of input parameter String name = req.getParameter("name");
// Acquisition of access time Date d = new Date(); String date = d.toString();
// Name and the access time are stored in the HttpServletRequest object req.setAttribute("name", name); req.setAttribute("date", date);
Application example
Class HelloPersonForward1 (2)
// Forward processing
RequestDispatcher rd =
req.getRequestDispatcher("/helloPersonForward2");
rd.forward(req , res);
Application example
Class HelloPersonForward2 (1)
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
System.out.println("doPost");
// Data is acquired from the HttpServletRequest object String name = (String)req.getAttribute("name"); String date = (String)req.getAttribute("date");
Application example
Class HelloPersonForward2 (2)
PrintWriter pw = res.getWriter(); pw.println("
pw.println("
Hello : " + name + "
"); pw.println("");
pw.println(" Access time : " + date + "
");
pw.println("
Communication between client and server
HTTP : stateless protocol With Web applications, it must save the state
of previous transactions : Example 1 : Provides a way to identify a user
across more than one page request
Example 2 : Client visit to a commercial Web site,
select the articles and pay for all
Cookie và session
Two kind of saving state of transaction :
Cookie : saving information on the side of client Session : saving information on the side of server
Cookie
The cookie is a mechanism that the data of
the Web application is preserved in a browser of the client
Server
Cookies
Servlet
Web Browser
Cookies
Cookie Example
Sent to server
Server add information
Cookie Example
testCookie.htm
Cookie on the client side
Cookie Example
CookieListing.java (1)
public class CookieListing extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { PrintWriter pw = res.getWriter(); pw.println("
Listing
pw.println("
Cookie received from client
");
Cookie[] cookies = req.getCookies(); for (int i=0; i< cookies.length; i++)
pw.println(cookies[i].getName() + " : " +
cookies[i].getValue());
Cookie Example
CookieListing.java (2)
pw.println("
Cookie received from server
");
Cookie ck = new Cookie("serverCookie", "serverCookieValue"); res.addCookie(ck);
pw.println(""); pw.println("
Session management
Server create a new session when client use a
Internet browser connecting to a Web application
Session exists until :
Client close Internet browser The connecting time exceed a default timeout
Notes :
When client open more than a Internet browser, each
browser is managed by one session
Session object manipulation
Each session is created by servlet container and
identified by a unique identification (id)
Request
Session Object Making
Client
Setting of Information
Response +
SessionID
Servlet Instance
Request +
SessionID
Response +
SessionID
Session Object: ID : xxxxxxx Information Searching session object Refer/Update of information
Session object manipulation
Session Object Making
Syntax :
public HttpSession getSession(boolean create)
Usage :
Returns the current HttpSession associated with
this request or,
if there is no current session and create is true,
returns a new session.
Session object manipulation
Usage example
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
… HttpSession session = req.getSession(true); …
}
Session object manipulation
Manipulation of Information
Information : Attributes
Name : String Value : Object
Setting of information
public void setAttribute(String name, Object value) Set value to the attribute specified by name Overwrite when the object of the same name exists
Acquisition of information
public Object getAttribute(String name) Return the Object of the attribute specified by name Return null if name doesn’t exist
Session object manipulation
Usage example
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException { … session.setAttribute("countHit", new Integer(count)); … Integer i = (Integer)session.getAttribute("countHit"); if (i != null) {
count = i.intValue() + 1;
} …
}
Deletion of information
Syntax :
public void removeAttribute(String name) Remove the attribute specified by name
Usage example :
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
… HttpSession session = req.getSession(true); …
session.removeAttribute(“countHit”);
}
Session Information (1)
creation time :
public long getCreationTime()
last accessed time :
public long getLastAccessedTime() measured in milliseconds since midnight January
1, 1970 GMT
Session Information (2)
maximum time interval :
public int getMaxInactiveInterval() public void setMaxInactiveInterval(int interval) the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session Invalidates this session public void invalidate()
Sample application
Another session
TestSession1.java (1)
public class TestSession1 extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
// take HttpSession object HttpSession session = req.getSession(true);
TestSession1.java (2)
// declare “count” to count the number of page hit int count = 1;
// take “countHit” attribute Integer i = (Integer)session.getAttribute("countHit"); if (i != null) count = i.intValue() + 1;
// set “countHit” attribute session.setAttribute("countHit", new Integer(count));
TestSession1.java (3)
PrintWriter pw = res.getWriter();
pw.println("
pw.println("Your session ID is " + session.getId() + "
");
pw.println("and you have hit this page " + count + " times during this browser session");
TestSession1.java (4)
pw.println("
");pw.println("
Handson exercise
Write an servlet to display information of a
session following this form :