310 likes | 444 Views
Servlet II. Web Application. ServletContext. The javax.servlet.ServletContext interface represents a Servlet’s view of the Web Application it belongs to.
E N D
Servlet II Web Application
ServletContext • The javax.servlet.ServletContext interface represents a Servlet’s view of the Web Application it belongs to. • Through the ServletContext interface, a Servlet can access raw input streams to Web Application resources, virtual directory translation, and an application scope for binding objects. • Individual container vendors provide specific implementations of ServletContext objects, but they all provide the same functionality defined by the ServletContext interface.
ServletConfig • Each servlet has an object called the ServletConfig. • Container creates the object which implements the javax.servlet.ServletConfig interface. • ServletConfigthat contains the initialization parameters. • A reference to this object can be retrieved by calling the getServletConfig() method. • The ServletConfig object provides the following methods for accessing initial parameters: • getInitParameter(String name) • Returns a String object that contains the value of the named initialization parameter or null if the parameter does not exist. • getInitParameterNames() • Returns the names of the Servlet’s initialization parameters as an Enumeration of String objects or an empty Enumeration if the Servlet has no initialization parameters.
Response Redirection • Sometimes Servlet take a user’s request and forward it any other resource on the Web. • The status code use for this is 302, “Resource Temporarily Moved”. • It informs a client that the resource they were looking for is not at the requested URL, but is instead at the URL specified by the Location header in the HTTP response. • Always use absolute redirections. Either use a complete URL such as: • response.sendRedirect("http://127.0.0.1/foo/bar.html"); • Or use an absolute URL from the root, “/”, of the Web Application • response.sendRedirect("/for/bar.html");
Auto Refreshing • Another response header technique is to send a wait page or a page that will auto-refresh to a new page after a given period of time. • Helpful in any case where a response might take an uncontrollable time to generate, or for cases where you want to ensure a brief pause in a response. • response.setHeader("Refresh", "time; URL=url" ); • “time” is replaced with the amount of seconds, the page should wait, • “url” is replaced with the URL that the page should eventually load • response.setHeader("Refresh", "10; URL=http://127.0.0.1/foo.html")
State • Managing state in a web application is an important concept for web programmers • When a browser sends a request to a server, the browser establishes a connection, sends an HTTP request, and consumes an HTTP response. • If the response is an HTML page, then the client will typically parse the page looking for other tags that require data to be downloaded (such as IMG or applet tags). • If there are such tags on the page, then the browser will re-use the same connection to download that data. • However, as soon as the page “transaction” is complete, the browser will close the connection. This has a major impact on the way Web Applications work. • Most applications maintain data on behalf of a user and need to track users.
Handling State in a Stateless Protocol • Rewriting the URL: • Servlets can use getParameter() and getParameterValues() of HttpServletRequest object • Server must rewrite every URL returned to the client with the client’s state info • <A HREF=“info.html?session=972368”>Course Information</A> • Hidden Variables • Hidden HTML form variables can be used to store state information: • <INPUT TYPE=“HIDDEN” NAME=“session” VALUE=“972368”> • Hidden variables are not shown to the user by the browser • Usually, a combination of Hidden Variables and URL Rewriting will do the trick
Handling State in a Stateless Protocol • Cookies (state only) • HTML mechanism for tracking user identity and preferences • Simple to use, (no URL rewriting, etc.) but... • All but useless for business-critical delivery because the user can choose to turn cookies off • Session Management (state and identity) • Client to return a piece of state information uniquely identifying the session with each request. • After a specific time period, the session is destroyed and invalidated or a user to manually terminate a session, usually through a logout button. • Session management is useful for storing large amounts of data, because only the SessionID is passed between the client and server.
Cookies • Cookies are small bits of textual information that • a server sends to a browser • the browser returns unchanged when visiting the same Web site or domain later • By having the server read information it sent the client previously, the site can provide visitors with a number of conveniences • Identifying a user during an e-commerce session • Avoiding username and password • Customizing a site • Focusing advertising
Placing Cookies using Response • A cookie is created by calling the Cookie constructor, which takes two strings: • The cookie name • The cookie value • Neither the name nor the value should contain whitespace or any of[ ] ( ) = , " / ? @ : ; • To send cookies to the client, a servlet would • Create one or more cookies with the appropriate names and values • Set any desired optional attributes • Add the cookies to the response headers Cookie userCookie = new Cookie("user", "uid1234"); // name, value response.addCookie(userCookie);
Reading Incoming Cookies import javax.servlet.http.*; String cookieName = “myCookie”; Cookies cookies[] = request.getCookies(); for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if(cookieName.equals(cookie.getName())) return(cookie.getValue()); }
Session Management • By default, Servlet session management is based on cookies, but the engine will resort to URL rewriting if cookies are unavailable • HttpServletRequestmethods for session management: • HttpSessiongetSession(): gets the HttpSession object attached to this request • HttpSessiongetSession(boolean): • booleanisRequestedSessionIdFromCookie(): is it derived from a cookie? • booleanisRequestedSessionIdFromURL(): is it from a URL? • booleanisRequestedSessionIdValid(): true if valid, false if invalid (i.e., expired)
Session Managementjavax.servlet.http.HttpSession • Object getAttribute (String) • Enumeration getAttributeNames() • removeAttribute(String) • setAttribute (Sring, Object) • String getId(): gets the sessionIDitself • long getCreationTime(): gets the time the session was created • long getLastAccessedTime(): gets the client’s last request time • booleanisNew(): returns true if this is a new session (first client access with this ID) • void setMaxInactiveInterval(int interval): sets the max number of seconds that a session is guaranteed to be held valid before it is expired by the Servlet engine. • void invalidate(): expires the current session
Example: HttpSession public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal();
Servlet Request • Contains data passed from client to servlet • All servlet requests implement ServletRequest interface which defines methods for accessing – Client sent parameters – Object-valued attributes – Locales – Client and server – Input stream – Protocol information – Content type
Getting Client Sent Parameters • A request can come with any number of parameters • Parameters are sent from HTML forms: – GET: as a query string, appended to a URL – POST: as encoded POST data, not appeared in the URL • getParameter("paraName” ) – Returns the value of paraName – Returns null if no such parameter is present – Works identically for GET and POST requests
A Sample FORM using GET <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Collecting Three Parameters</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">Please Enter Your Information</H1> <FORM ACTION="/sample/servlet/ThreeParams"> First Name: <INPUT TYPE="TEXT" NAME="param1"><BR> Last Name: <INPUT TYPE="TEXT" NAME="param2"><BR> Class Name: <INPUT TYPE="TEXT" NAME="param3"><BR> <CENTER> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY> </HTML>
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your Information"; out.println("<HTML>" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<UL>\n" + " <LI><B>First Name in Response</B>: “ + request.getParameter("param1") + "\n" + " <LI><B>Last Name in Response</B>: “ + request.getParameter("param2") + "\n" + " <LI><B>NickName in Response</B>: “ + request.getParameter("param3") + "\n" + "</UL>\n" + "</BODY></HTML>"); } }
Getting Misc. Information • Servlet can get client information from the request • String request.getRemoteAddr() Get client's IP address • String request.getRemoteHost() Get client's host name • Servlet can get server's information: • String request.getServerName() ? e.g. "www.sun.co"m • intrequest.getServerPort() ? e.g. Port number "8080"
Getting Misc. Information • Input stream • ServletInputStreamgetInputStream() • java.io.BufferedReadergetReader() • Protocol • java.lang.StringgetProtocol() • Content type • java.lang.StringgetContentType() • Is secure or not (if it is HTTPS or not) • booleanisSecure()
Servlet Response • Contains data passed from servlet to client • All servlet responses implement ServletResponse interface • Retrieve an output stream • Indicate content type • Indicate whether to buffer output • Set localization information • HttpServletResponse extends ServletResponse • HTTP response status code • Cookies
Response Status Codes • response.setStatus(intstatusCode) • Status codes are defined in HttpServletResponse • Status codes are numeric fall into five general categories: • 100-199 Informational • 200-299 Successful • 300-399 Redirection • 400-499 Incomplete • 500-599 Server Error • Default status code is 200 (OK)
Response Header • Give forwarding location • Specify cookies • Supply the page modification date • Instruct the browser to reload the page after a designated interval • Give the file size so that persistent HTTP connections can be used • Designate the type of document being generated • …
Response Headers Methods • public void setHeader( String headerName, String headerValue) – Sets an arbitrary header. • public void setDateHeader( String name, long millisecs) – Converts milliseconds since 1970 to a date string in GMT format • public void setIntHeader( String name, intheaderValue) – Prevents need to convert int to String before calling setHeader • addHeader, addDateHeader, addIntHeader – Adds new occurrence of header instead of replacing.