The document discusses servlet configuration and initialization parameters. It describes how servlets use the init() method for one-time initialization tasks, such as loading data or establishing database connections. Initialization parameters can be passed to servlets through the web.xml deployment descriptor and accessed using the ServletConfig interface. The document also covers using the ServletContext interface to define context-wide initialization parameters and attributes. Finally, it briefly discusses session management and how cookies can be used to track state across HTTP requests.
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
117 views
Servlet Config and Context
The document discusses servlet configuration and initialization parameters. It describes how servlets use the init() method for one-time initialization tasks, such as loading data or establishing database connections. Initialization parameters can be passed to servlets through the web.xml deployment descriptor and accessed using the ServletConfig interface. The document also covers using the ServletContext interface to define context-wide initialization parameters and attributes. Finally, it briefly discusses session management and how cookies can be used to track state across HTTP requests.
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64
SERVLET CONFIGURATION
How to configure servlet for initial parameters
The init Method Most of the time, your servlets deal only with per-request data, and doGet or doPost are the only life-cycle methods we need. However, we want to perform complex setup tasks when the servlet is first loaded, but not repeat those tasks for each request. The init method is designed for this case; it is called when the servlet is first created, and not called again for each user request. The init Method It is used for one-time initializations, just as with the init method of applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, The init method definition looks like this: public void init() throws ServletException { // Initialization code... } The init method performs two varieties of initializations: general initializations and initializations controlled by initialization parameters.
General Initializations With the first type of initialization, init simply creates or loads some data that will be used throughout the life of the servlet, or it performs some one-time computation. Servlet examples include setting up a database connection pool for requests that the servlet will handle or loading a data file into a HashMap. GeneralInitServlet public class ShowGeneralInitServlet extends HttpServlet { private static final long serialVersionUID = 1L; private long modTime; private int[] numbers = new int[10];
public void init() throws ServletException { // Round to nearest second (i.e., 1000 milliseconds) modTime = System.currentTimeMillis() / 1000 * 1000; for (int i = 0; i < numbers.length; i++) { numbers[i] = randomNum(); } } GeneralInitServlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your Randomly Generated Numbers"; String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<B> " + "We have stored the following " + numbers.length + " numbers for you.</B>" + "<OL>"); for (int i = 0; i < numbers.length; i++) { out.println(" <LI>" + numbers[i]); } out.println("</OL>" + "</BODY></HTML>"); }
GeneralInitServlet /** The standard service method compares this date against * any date specified in the If-Modified-Since request header. * If the getLastModified date is later or if there is no * If-Modified-Since header, the doGet method is called * normally. But if the getLastModified date is the same or * earlier, the service method sends back a 304 (Not Modified) * response and does <B>not</B> call doGet. The browser should * use its cached version of the page in such a case. */ public long getLastModified(HttpServletRequest request) { return(modTime); }
private int randomNum() { return((int)(Math.random() * 100)); }
} Initializations Controlled by Initialization Parameters
To understand the motivation for init parameters, we need to understand the categories of people who might want to customize the way a servlet or JSP page behaves. There are three such groups: 1. Developers. 2. End users. 3. Deployers.
Initializations Controlled by Initialization Parameters (contd) Developers change the behavior of a servlet by changing the code. End users change the behavior of a servlet by providing data to an HTML form (assuming that the developer has written the servlet to look for this data). For Deployers, there needs to be a way to let administrators move servlets from machine to machine and change certain parameters (e.g., the address of a database, the size of a connection pool, or the location of a data file) without modifying the servlet source code. Providing this capability is the purpose of init parameters. Initializations Controlled by Initialization Parameters (contd) Because the use of servlet initialization parameters relies heavily on the deployment descriptor (web.xml), we use following classes to do initialization in init method: ServletConfig ServletContext ServletConfig public interface ServletConfig A servlet configuration object used by a servlet container used to pass information to a servlet during initialization. That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.
ServletConfig Methods java.lang.String getInitParameter(java.lang.String name) Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. java.util.Enumeration 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. ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing. java.lang.String getServletName() Returns the name of this servlet instance. Config Parameters in web.xml <servlet> <servlet-name>ConfigServlet</servlet-name> <servlet-class>mca.servlet.ConfigServlet</servlet-class> <init-param> <param-name>email</param-name> <param-value>[email protected]</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ConfigServlet</servlet-name> <url-pattern>/ConfigServlet</url-pattern> </servlet-mapping> How to access Config Values protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println(getServletConfig().getInitParameter("email")); } ServletContext public interface ServletContext ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. To get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web application is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM. ServletContext Methods java.lang.Object getAttribute(java.lang.String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name. java.util.Enumeration getAttributeNames() Returns an Enumeration containing the attribute names available within this servlet context. ServletContext getContext(java.lang.String uripath) Returns a ServletContext object that corresponds to a specified URL on the server. java.lang.String getInitParameter(java.lang.String name) Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. java.util.Enumeration getInitParameterNames() Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. int getMajorVersion() Returns the major version of the Java Servlet API that this servlet container supports. java.lang.String getMimeType(java.lang.String file) Returns the MIME type of the specified file, or null if the MIME type is not known. Example in web.xml <context-param> <param-name>globalVariable</param- name> <param-value>username</param-value> </context-param> How to access value in Servlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println(getServletContext().getInitParamet er("globalVariable"));
} TRACKING STATE Session Management Provide state between HTTP requests Client-side Cookies Hidden variables URL rewriting User authentication getRemoteUser() Provided by HttpServletRequest Server-side Servlets built-in session tracking A Cookie is data (String) that the server passes to the browser and the browser stores on the server Set of name value pairs Web servers place cookies on user machines with id to track the users Two types of cookies Persistent cookies: Stored on hard drive in text format Non-persistent cookies: Stored in memory and goes away after you reboot or turn off the machine
Cookies Persistent Cookies Stored at the browser As name=value pairs Browsers limit the size of cookies Users can refuse to accept them Attached to subsequent requests to the same server Servlets can create cookies Included in the HTTP response header Attributes of a cookie Name: Name of a cookie Value: Value of the cookie Comment: Text explaining purpose of cookie Max-Age: Time in seconds after which the client should not send cookie back to server Domain: Domain to which the cookie should be sent Path: The path to which the cookie should be sent Secure: Specifies if cookie should be sent via https Version: Cookie version (0 original Netscape version of Cookie 1 cookies standardized via RFC 2109) Cookie Attributes Retrieving Cookies HttpServletRequest public Cookie[] getCookies() Cookie getName() getValue() getDomain() getPath() getSecure() Cookie Example protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; response.setContentType("text/html"); out = response.getWriter(); Cookie cookie = new Cookie("CName", "Cookie Value"); cookie.setMaxAge(100); response.addCookie(cookie);
out.println("<HTML><HEAD><TITLE>"); out.println(" Use of cookie in servlet"); out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>"); out.println(" <b>This is a Cookie example</b>"); out.println("</BODY></HTML>"); out.close(); } package edu.albany.mis.goel.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Cookie; import javax.servlet.ServletException; public class CookieServlet extends HttpServlet { protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { CookieServlet Cookie[] cookies = request.getCookies(); Cookie token = null; if(cookies != null) { for(int i = 0; i < cookies.length; i++) {
if(cookies[i].getName().equals("tok en")) { // Found a token cookie token = cookies[i]; break; } } } response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><head><title>Tokens</title></head><body "); String reset = request.getParameter("reset"); System.out.println("token = " + token); if (token == null || (reset != null && reset.equals("yes"))) { Random rand = new Random(); long id = rand.nextLong(); writer.println("<p>Welcome. A new token " + id + " is now established</p>"); // Set the cookie token = new Cookie("token", Long.toString(id)); token.setComment("Token to identify user"); token.setMaxAge(-1); token.setPath("/cookie/track");
Cookies (Token) response.addCookie(token); } else { writer.println("Welcome back. Your token is " + token.getValue() + ".</p>"); } String requestURLSame = request.getRequestURL().toString(); String requestURLNew = request.getRequestURL() + "?reset=yes"; writer.println("<p>Click <a href=" + requestURLSame + ">here</a> again to continue browsing with the same identity.</p>"); writer.println("<p>Otherwise, click <a href=" + requestURLNew + ">here</a> again to start browsing with a new identity.</p>"); writer.println("</body></html>"); writer.close(); } }
Cookies, contd. http:// www.address.edu:1234/path/subdir/file.ext?query_string Service http Host www. Address. edu Port 1234 /path/subdur/file.ext resource path on the server query_string additional information that can be passed to resource Http allows name value pairs to be passed to the resource http:// www.test.edu/index.jsp?firstname=sanjay+lastname=goel The server can place the id of a customer along with the URL http://www.fake.com/ordering/id=928932888329938.823948 This number can be obtained by guessing or looking over some ones shoulder Timeout for the sessions may be a few hours User can masquerade as the owner of the id and transact on the web URL Encoding package edu.albany.mis.goel.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; public class TokenServlet extends HttpServlet { protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // Get the token from the request String tokenID = request.getParameter("tokenID"); // Prepare for response response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><head><title>Tokens</title></head><body "); writer.println("style=\"font-family:verdana;font-size:10pt\">"); }
URL Rewriting if (tokenID == null) { // Client did not sent any token Random rand = new Random(); tokenID = Long.toString(rand.nextLong()); writer.println("<p>Welcome. A new token " + tokenID + " is now established</p>"); } else { // Client sent the token back writer.println("<p>Welcome back. Your token is " + tokenID + ".</p>"); // Prepare links for sending requests back String requestURLSame = request.getRequestURL().toString() + "?tokenID=" + tokenID; String requestURLNew = request.getRequestURL().toString(); // Write the response and close writer.println("<p>Click <a href=" + requestURLSame + ">here</a> again to continue browsing with the same identity.</p>"); writer.println("<p>Otherwise, click <a href=" + requestURLNew + ">here</a> again to start browsing with a new identity.</p>"); writer.println("</body></html>"); writer.close(); } } HTML allows creation of hidden fields in the forms Developers use hidden fields to store information for their reference ID can be stored as a hidden form field <Input Type=Hidden Name=Search Value=key> <Input Type=Hidden Name=id Value=123429823> Hidden Form Fields Login.jsp "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login</title> </head> <body> <h1>Login</h1> Please enter your username and password <form action="HiddenFormFieldServlet" method="POST"> <p><input type="text" name="username" > <p><input type="password" name="password"> <p><input type="hidden" name="param" value="12"> <p><input type="submit" value="Submit"> </form>
</body> </html> Hidden Form Field
// Get the parameter from the request String username = request.getParameter("username"); String password = request.getParameter("password"); String hiddenparam = request.getParameter("param"); System.out.println("Hidden Parameter value:: " + hiddenparam); LoginService loginService = new LoginService(); boolean result = loginService.authenticateUser(username, password); if (result){ response.sendRedirect("success.jsp"); } else{ response.sendRedirect("login.jsp"); }
Servlets Built-in Session Tracking
Session tracking API Devoted to servlet session tracking Most servers support session tracking Through the use of persistent cookies Able to revert to URL rewriting when cookies fail Servlet uses the token to fetch session state Session objects are maintained in memory Some servers allow them to be written to file system or database as memory fills up or when server shuts down Items in the session need to be serializable Session Management HTTP is a stateless protocol. Each request and response stand alone Without session management, each time a client makes a request to a server, its brand new user with a brand new request from the servers point of view. A session refers to the entire interaction between a client and a server from the time of the clients first request, which generally begins the session, to the time the session is terminated. Session Tracking Basics Every user of a site is associated with a javax.servlet.http.HttpSession object To store and retrieve information about the user Retrieve the current HttpSession object public HttpSession HttpServletRequest.getSession() Creates one if no valid session found Session Attributes To add data to a session object public void HttpSession.setAttribute(String name,Object value) To retrieve an object from a session public Object HttpSession.getAttribute(String name) To get the names of all objects in a session public Enumeration HttpSession.getAttributeNames() To remove an object from a session public void HttpSession.removeAttribute(String name) Provides methods to establish session between client and server Session lasts for a specified time Allows binding of objects over multiple requests Important Methods getID() getAttribute(String name) getAttriubuteNames() setAttribute(String name, Object value) removeAttribute(String name) inValidate() HttpSession Interface Session Lifecycle Sessions do not last forever Expire automatically due to inactivity Default 30 min Explicitly invalidated by servlet When session expires (or is invalidated) The HttpSession object and its data values are removed HttpSession Lifecycle Methods 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 invalidate() Invalidates this session then unbinds any objects bound to it 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, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request Setting Session Timeout Setting default session timeout Deployment descriptor, web.xml Applies to all sessions created in the given web application <session-config> <session-timeout> 30 <! minutes --> </session-timeout> </session-config> Configured individually public void HttpSession.setMaxInactiveInterval(int secs) public int HttpSession.getMaxInactiveInterval() Terminating a session session.invalidate() Deletes session related attributes form server Removes cookie from client The Session Tracking API // The session object associated with this user/browser is available // to other servlets.
/** Initalises the StringBuffer Objects. */ public HTMLTable() { head = new StringBuffer(); head.append("<table width=\"90%\" align=\"center\">"); head.append("<tr><th width=\"50%\" bgcolor=\"lightgrey\">Attribute</td>"); head.append("<th width=\"50%\" bgcolor=\"lightgrey\">Value</td></tr>"); rows = new StringBuffer(); foot = new StringBuffer(); foot.append("</table>"); } HTMLTable Class /** Appends the attribute and value in a row to the HTML table StringBuffer. * @param attribute The first column value. * @param value The second column value. */ public void appendTitleRow(String attribute) { rows.append("<tr><td colspan=2><b><u>").append(attribute); rows.append("</u></b></td></tr>"); } /** Appends the attribute and value in a row to the HTML table StringBuffer. * @param attribute The first column value. * @param value The second column value. */ public void appendRow(String attribute, String value) { rows.append("<tr><td>").append(attribute); rows.append("</td><td><code>").append(value).append("</code></td></tr>"); } /** Appends the attribute and value in a row to the HTML table StringBuffer. * @param attribute The first column value. * @param value The second column value. */ public void appendRow(String attribute, int value) { appendRow(attribute, new Integer(value).toString()); } HTMLTable Class, contd. /** Appends the attribute and value in a row to the HTML table StringBuffer * @param attribute The first column value. * @param value The second column value. */ public void appendRow(String attribute, boolean value) { appendRow(attribute, new Boolean(value).toString()); } /** Overrides Object.toString method to present a String representation of the HTML table built up. * @return value The second column value. */ public String toString() { return head.append(rows).append(foot).toString(); } /** Presents a StringBuffer representation of the HTML table built up. * @return value The second column value. */ public StringBuffer toStringBuffer(){ return head.append(rows).append(foot); } }
ShoppingCart.class Catalog.class lib/ xereces.jar xalan.jar mca/servlets/ ShoppingCart.java Catalog.java Structure of Web Application Public Resources that are downloaded directly to the client without processing Lib files are standard libraries that the code may need JSP files are an exception since they are converted to servlets and not downloaded directly Files which the web container processes but not client Lib files are standard libraries that the code may need Source Files which are developed by the user Package directory reduces chances of name conflicts Web applications are deployed in the web applications directory of the web server In tomcat this directory is ${Tomcat_Home}/webapps Two separate ways of deploying web applications Exploded Directory Format Development directory is copied to the application directory of the web server Used primarily in development mode when changes are frequent Web Application Archive (WAR) Format Archived version of development directory is copied to application directory of web server Created using jar utility i.e. jar cv0f SimpleWebApp.war . Deployment of Web Applications If web application is in a location different than the webapps directory context is defined Location: ${Tomcat_Home}/conf/server.xml <context path=/store docBase=/store.war reloadable=true> Context declares a context to exist with a base URL path of /store The application can be accessed at http://localhost:8080/store/. docBase tells tomcat where to find the web application Relative path (/store.war) tells Tomcat that store.war is at the top level of the webapps directory An absolute path can also be supplied I.e. c:/myapps/store.war Reloadable set to true indicates that if the class or lib files change the application detects the change Deployment of Web Applications, contd. Each application in a web container is associated with a context All web resources are associated with the context. Servlet context is rooted at a known path within web container. (e.g. {Tomcat_Home}/webapps/store/home.html) Context for this application is /store User would access this as: http://localhost:8080/store/home.html There is a special object called servlet context. A sandbox for the application (prevents name clashes and efficient downloading of classes without having to set classpath) Allows servlets access container resources Primary use of servlet context is to share attributes between servlets in an application. Context may be defined explicitly in a web server Configuration Directory in Tomcat: ${Tomcat_Home}/conf/server.xml <context path=/examples docBase=examples debug=0 reloadable=true> ServletContext Conveys configuration information of a web application The primary elements of a deployment descriptor file Servlet definitions & mappings Servlet context initialization parameters Error pages Welcome pages File based security Rules for the deployment descriptor file Resides at the top level of the WEB-INF directory Must be a well formed XML file called web.xml Must conform to the dtd (located at http://java.sun.com/dtd/web-app-2-3.dtd) Deployment Descriptor Header denotes the version of XML <?xml version="1.0" encoding="ISO-8859-1"?> Describes the the DTD for the application <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" http://java.sun.com/dtd/web-app_2_3.dtd"> Description of the application enclosed in web-app tags <web-app> Contents of the file <web-app> Deployment Descriptors - Header Context parameters are parameters that are related to the entire application. Any number of initialization parameters can be provided in the context One initialization parameter for web application is shown below: <context-param> <param-name> adminEmail </param-name> <param-vlaue> [email protected] </param-value> </context-param> ServletContext object is used to obtain context information e.g. String adminEmail = getServletContext().getInitParameter(adminEmail); The methods in ServletContext are abstract, their implementations must be provided by the web container. Deployment Descriptors - Context Servlet mappings map servlets to specific URL pattern <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/home.html<url-pattern> </servlet-mapping> Allows web container to send requests to specific servlet Why is servlet mapping required? A logical way to specify servlets would be to use context/servletname (i.e. http://localhost:8080/store/storeservlet) Allows multiple urls to be mapped to same servlet Allows implementation details to be hidden Servlets can be mapped to more than one URL thro the use of wildcards in <url-pattern> e.g. <servlet-mapping> <servlet-name>ValadatorServlet<servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> The previous example maps every URL encountered to the same servlet Deployment Descriptors - Servlets Error pages allow the application to specify pages to be shown when particular errors occur Used for Java Exceptions and Http Errors. The error page shown below is displayed when the server encounters a java.lang.ArithmeticException. <error-page> <exception-type> java.lang.ArithmeticExceception </exception-type> Exception Type <location>/error.html</location> Resource to Show </error-page> The error page shown below is displayed when the server encounters a an Http error <error-page> <error-code>404</error-code> Http Error Code <location>/404.html</location> Resource to Show </error-page>