Servelets ppt


Published on

Published in: Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Servelets ppt

  1. 1. CSIE33000 Net Programming Lecture11 Java Servelet Lecture 15: Servelets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun What is a Servlet? A Servlet is a Java program that extends the capabilities of servers. Inherently multi-threaded. Each request launches a new thread. Input from client is automatically parsed into a Request variable. A servlet can be thought of as a server-side applet Applet: a java program that runs within the web browser Servlet: a java program that runs within the web server Servlets are loaded and executed by a web server in the same manner that applets are loaded and executed by a web browser CSIE33000 Network Programming Servelets 2 Shiow-yang Wu Note 1
  2. 2. CSIE33000 Net Programming Lecture11 Java Servelet Server-Side Application Architecture Applications Dynamic generates HTML pages Access to database and/or back-end servers etc. CSIE33000 Network Programming Servelets 3 Server-Side Application: CGIs Common Gateway Interface (CGI) Basically call external program Use standard input and output for data exchange Programming language independent Weakness CGI program may not be easily portable to other platform Substantial overhead is incurred in starting the CGI process CSIE33000 Network Programming Servelets 4 Shiow-yang Wu Note 2
  3. 3. CSIE33000 Net Programming Lecture11 Java Servelet Servlet Architecture HTTP request Client Web Servlet (web browser) Server Containter Servlet HTTP response The client makes a request via HTTP The web server receives the requests and forwards it to the servlet If the servlet has not yet been loaded, the web server loads it into the JVM and executes it The servlet receives the HTTP request and performs some type of process The servlet returns a response to the web server The web server forwards the response to the client CSIE33000 Network Programming Servelets 5 Why Use Servlets Servlets are designed to replace CGI scripts Platform-independent and extensible CGI scripts are typically written in Perl or C, and are very much tied to a particular server platform Servlet is written in Java, which can easily integrate with existing legacy systems through RMI, CORBA, and/or JNI Persistent and fast Servers are loaded only once by the web server and can maintain services between requests (particularly important for maintaining database connections) CGI scripts are transient – a CGI script is removed from memory after it is complete For each browser request, the web server must spawn a new operating system process Secure The only way to invoke a servlet from the outside world is through a web server, which can be protected behind a firewall CSIE33000 Network Programming Servelets 6 Shiow-yang Wu Note 3
  4. 4. CSIE33000 Net Programming Lecture11 Java Servelet What can you build with servlets Search engines E-commerce applications Shopping carts Product catalogs Personalization systems Intranet application Groupware applications: bulletin boards, file sharing, etc. CSIE33000 Network Programming Servelets 7 Steps of Servlet Processing 1. Read any data sent by the server Capture data submitted by an HTML form 2. Look up any HTTP information Determine the browser version, host name of client, cookies, etc. 3. Generate the results Connect to databases, connect to legacy applications, etc. 4. Format the results Generate HTML on the fly 5. Set the appropriate HTTP headers Tell the browser the type of document being returned or set any cookies 6. Send the document back to the client CSIE33000 Network Programming Servelets 8 Shiow-yang Wu Note 4
  5. 5. CSIE33000 Net Programming Lecture11 Java Servelet Servlet Life Cycle Create (Servlet Instantiation): Loading the servlet class and creating a new instance Initialize (Servlet Initialization): Initialize the servlet using the init() method Service (Servlet processing): Handling 0 or more client requests using the service() method Destroy (Servlet Death): Destroying the servlet using the destroy() method When HTTP calls for a servlet Not loaded: Load, Create, Init, Service Already loaded: Service CSIE33000 Network Programming Servelets 9 Client Servlet- Form:Client Enabled:Server Lookup Static Page or Launch Process/Thread Http Request to Create Output Lookup Launch On first access Servlet launch the servlet program. Launch Http Response Thread for Client Launch separate Http thread to service Response each request. CSIE33000 Network Programming Servelets 10 Shiow-yang Wu Note 5
  6. 6. CSIE33000 Net Programming Lecture11 Java Servelet Writing Servlets Install a web server capable of launching and managing servlet programs. Install the javax.servlet package to enable programmers to write servlets. Ensure CLASSPATH is changed to correctly reference the javax.servlet package. Define a servlet by subclassing the HttpServlet class and adding any necessary code to the doGet() and/or doPost() and if necessary the init() functions. CSIE33000 Network Programming Servelets 11 Handler Functions Each HTTP Request type has a separate handler function. GET -> doGet(HttpServletRequest, HttpServletResponse) POST -> doPost(HttpServletRequest, HttpServletResponse) PUT -> doPut (HttpServletRequest, HttpServletResponse) DELETE -> doDelete (HttpServletRequest, HttpServletResponse) TRACE -> doTrace (HttpServletRequest, HttpServletResponse) OPTIONS -> doOptions (HttpServletRequest, HttpServletResponse) CSIE33000 Network Programming Servelets 12 Shiow-yang Wu Note 6
  7. 7. CSIE33000 Net Programming Lecture11 Java Servelet A Servlet Template import*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g. cookies) and HTML form data (e.g. data the user // entered and submitted). // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to browser } } CSIE33000 Network Programming Servelets 13 Important Steps Import the Servlet API: import javax.servlet.*; import javax.servlet.http.*; Extend the HTTPServlet class Full servlet API available at: You need to overrride at least one of the request handlers! Get an output stream to send the response back to the client All output is channeled to the browser. CSIE33000 Network Programming Servelets 14 Shiow-yang Wu Note 7
  8. 8. CSIE33000 Net Programming Lecture11 Java Servelet doGet and doPost The handler methods each take two parameters: HTTPServletRequest: encapsulates all information regarding the browser request. Form data, client host name, HTTP request headers. HTTPServletResponse: encapsulate all information regarding the servlet response. HTTP Return status, outgoing cookies, HTML response. If you want the same servlet to handle both GET and POST, you can have doGet call doPost or vice versa. Public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {doPost(req,res);} CSIE33000 Network Programming Servelets 15 Hello World Servlet import*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>n" + "<BODY>n" + "<H1>Hello WWW</H1>n" + "</BODY></HTML>"); } } CSIE33000 Network Programming Servelets 16 Shiow-yang Wu Note 8
  9. 9. CSIE33000 Net Programming Lecture11 Java Servelet Running Servlets Jakarta/Apache Tomcat Supercedes Java Apache and JServ Macromedia JRun ServletExec Weblogic Borland Enterprise Application Server/JBuilder Java Servlet Development Kit (JSDK) CSIE33000 Network Programming Servelets 17 Single Threaded Example By default, uses shared threads Single instance of servlet shared by all requests One thread created for each request Class & instance variables are thread-unsafe; auto variables are thread-safe In some applications, you have to use single thread model, which Results in new servlet for each request Allows use of instance variables w/o synchronization CSIE33000 Network Programming Servelets 18 Shiow-yang Wu Note 9
  10. 10. CSIE33000 Net Programming Lecture11 Java Servelet Single Threaded Example import*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet implements javax.servlet.SingleThreadModel { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { // Code here! } } CSIE33000 Network Programming Servelets 19 Environment Access in HTTPServletRequest getContentLength() getServletPath() getContentType() getPathInfo() getProtocol() getPathTranslated() getServerName() getQueryString() getServerPort() getRemoteUser() getRemoteAddr() getAuthType() getRemoteHost() getHeader(“HdrStr”) getMethod() CSIE33000 Network Programming Servelets 20 Shiow-yang Wu Note 10
  11. 11. CSIE33000 Net Programming Lecture11 Java Servelet Parameter Access in HTTPServletRequest GetScheme GetHeader GetInputStream getIntHeader, getDateHeader GetParameter GetSession GetParameterValues GetRequestedSessionId GetParameterNames IsRequestedSessionIdValid GetReader isRequestedSessionIDFromCookie GetCharacterEncoding IsRequestedSessionIDFromUrl GetContentType GetHeaderNames GetCookies GetRequestURI GetHeaderNames CSIE33000 Network Programming Servelets 21 HTTPResponse Methods GetOutputStream SendError GetWriter SendRedirect GetCharacterEncoding SetHeader SetContentLength setIntHeader, SetContentType setDateHeader AddCookie SetStatus ContainsHeader encodeURL, encodeRedirectURL CSIE33000 Network Programming Servelets 22 Shiow-yang Wu Note 11
  12. 12. CSIE33000 Net Programming Lecture11 Java Servelet getParameter() Use getParameter() to retrieve parameters from a form by name. Named Field values HTML FORM <INPUT TYPE="TEXT" NAME="diameter"> In a Servlet String sdiam = request.getParameter("diameter"); CSIE33000 Network Programming Servelets 23 getParameter() cont’d getParameter() can return three things: String: corresponds to the parameter. Empty String: parameter exists, but no value provided. null: Parameter does not exist. CSIE33000 Network Programming Servelets 24 Shiow-yang Wu Note 12
  13. 13. CSIE33000 Net Programming Lecture11 Java Servelet getParameterValues() Used to retrieve multiple form parameters with the same name. For example, a series of checkboxes all have the same name, and you want to determine which ones have been selected. Returns an array of Strings. CSIE33000 Network Programming Servelets 25 getParameterNames() Returns an Enumeration object. By cycling through the enumeration object, you can obtain the names of all parameters submitted to the servlet. Note that the Servlet API does not specify the order in which parameter names appear. CSIE33000 Network Programming Servelets 26 Shiow-yang Wu Note 13
  14. 14. CSIE33000 Net Programming Lecture11 Java Servelet Circle Servlet import*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class circle extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) Specify HTML throws ServletException, IOException { output. response.setContentType("text/html"); Attach a PrintWriter out = response.getWriter(); PrintWriter to Response Object CSIE33000 Network Programming Servelets 27 Circle Servlet out.println("<BODY><H1 ALIGN=CENTER> Circle Info </H1>n"); try{ String sdiam = request.getParameter("diameter"); double diam = Double.parseDouble(sdiam); out.println("<BR><H3>Diam:</H3>" + diam + "<BR><H3>Area:</H3>" + diam/2.0 * diam/2.0 * 3.14159 + "<BR><H3>Perimeter:</H3>" + 2.0 * diam/2.0 * 3.14159); } catch ( NumberFormatException e ){ out.println("Please enter a valid number"); } out.println("</BODY></HTML>"); } CSIE33000 Network Programming Servelets 28 Shiow-yang Wu Note 14
  15. 15. CSIE33000 Net Programming Lecture11 Java Servelet Session Tracking Many applications need to maintain state across a series of requests from the same user (or originating from the same browser), e.g., When clients at an on-line store add an item to their shopping cart, how does the server know what’s already in the cart? When clients decide to proceed to checkout, how can the server determine which previously created shopping cart is theirs? HTTP is a stateless protocol Each time, a client talks to a web server, it opens a new connection Server does not automatically maintains “conversational state” of a user CSIE33000 Network Programming Servelets 29 Session Tracking Mechanisms Three mechanisms of session tracking Cookies URL rewriting Hidden form fields CSIE33000 Network Programming Servelets 30 Shiow-yang Wu Note 15
  16. 16. CSIE33000 Net Programming Lecture11 Java Servelet What is Cookie Cookie is a small amount of information sent by a servlet to a web browser Saved by the browser, and later sent back to the server in subsequent requests A cookie has a name, a single value, and optional attributes (name/value pair) A cookie’s value can uniquely identify a client Server uses cookie’s value to extract information about the session from some location on the server CSIE33000 Network Programming Servelets 31 Cookies and Servlets The HttpServletRequest class includes the “getCookies()” function. This returns an array of cookies, or null if there aren’t any. Cookies can then be accessed using three methods. String getName() String getValue() String getVersion() CSIE33000 Network Programming Servelets 32 Shiow-yang Wu Note 16
  17. 17. CSIE33000 Net Programming Lecture11 Java Servelet Cookies & Servlets cont’d Cookies can be created using HttpServletResponse.addCookie() and the constructor new Cookie(String name, String value); Expiration can be set using setMaxAge(int seconds) CSIE33000 Network Programming Servelets 33 Cookie Servlet public class CookieTest extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { OutputStream out = res.getOutputStream(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); Cookie[] cookies = req.getCookies(); Cookie current = null; if (cookies != null) { for (int i=0; i < cookies.length; i++) { pw.println("name=“ + cookies[i].getName()); pw.println("value=“ + cookies[i].getValue()); pw.println("version=“ + cookies[i].getVersion()); if (cookies[i].getName().equals("cookie")) { current=cookies[i]; } pw.println(); } } CSIE33000 Network Programming Servelets 34 Shiow-yang Wu Note 17
  18. 18. CSIE33000 Net Programming Lecture11 Java Servelet Cookie Servlet int count=0; if (current != null) { count = Integer.parseInt(current.getValue()); res.addCookie(new Cookie("previouscookie", new Integer(count).toString())); count++; } pw.println("Value stored in cookie = "+count); pw.flush(); pw.close(); count++; res.addCookie(new Cookie("cookie", new Integer(count).toString())); } } CSIE33000 Network Programming Servelets 35 Cookies as Session Tracking Mechanism Advantage Very easy to implement Highly customable Persist across browser shut-downs Disadvantage Users may turn off cookies for privacy or security reason Not quite universal browser support CSIE33000 Network Programming Servelets 36 Shiow-yang Wu Note 18
  19. 19. CSIE33000 Net Programming Lecture11 Java Servelet Sessions & Servlets Servlets also support simple transparent sessions Interface HttpSession Get one by using HttpServletRequest.getSession() You can store & retrieve values in the session putValue(String name, String value) String getValue(String name) String[] getNames() CSIE33000 Network Programming Servelets 37 Sessions & Servlets cont’d Various other information is stored long getCreationTime() String getId() long getLastAccessedTime() Also can set timeout before session destruction int getMaxInactiveInterval() setMaxInactiveInterval(int seconds) CSIE33000 Network Programming Servelets 38 Shiow-yang Wu Note 19
  20. 20. CSIE33000 Net Programming Lecture11 Java Servelet URL Rewriting URLs can be rewritten or encoded to include session information URL rewriting usually includes a session ID Session ID can be sent as an added parameters: http://.../servlet /Rewritten?sessionid=678 CSIE33000 Network Programming Servelets 39 URL Rewriting as Session Tracking Advantages Users remain anonymous There are universal support Disadvantages Tedious to rewrite all URLs Only works for dynamically created documents CSIE33000 Network Programming Servelets 40 Shiow-yang Wu Note 20
  21. 21. CSIE33000 Net Programming Lecture11 Java Servelet Hidden Form Fields Hidden form fields do not display in the browser, but can be sent back to the server by submit <INPUT TYPE=“HIDDEN” Name=“session” Value =‘…’> Fields can have identification (session id) or just something to remember Servlet reads the fields using request.getParameter() CSIE33000 Network Programming Servelets 41 Hidden Form Fields as Session Tracking Advantages Universally supported Allow anonymous users Disadvantages Only works for a sequence of dynamically generated forms Breaks down with static documents, emailed documents, bookmarked documents Cannot support browser shutdown CSIE33000 Network Programming Servelets 42 Shiow-yang Wu Note 21
  22. 22. CSIE33000 Net Programming Lecture11 Java Servelet Steps of Doing Session Tracking Programmers have to do the following steps in order to use the aforementioned tracking mechanisms: Generating and maintaining a session id for each session Passing session id to client via either cookie or URL Extracting session id either from cookie or URL Creating and maintaining a hashtable in which session id and session information are stored Coming up with a scheme in which session information can be added or removed These mechanisms can pass “session id”, but do not provide high-level programming APIs do not provide a framework from managing sessions CSIE33000 Network Programming Servelets 43 “Session Tracking” Features of Servlet Provides higher-level API for session tracking Built on top of cookie or URL rewriting Servlet container maintains Internal hashtable of session ids Session information in the form of HttpSession Provides a simple API for adding and removing session information (attributes) to HttpSession Could automatically switch to URL rewriting if cookies are unsupported or explicitly disabled CSIE33000 Network Programming Servelets 44 Shiow-yang Wu Note 22
  23. 23. CSIE33000 Net Programming Lecture11 Java Servelet HttpSession To get a user’s existing or new session object: HttpSession session = request.getSession(true) flag = true to create a new session if none exists HttpSession is a java interface containing methods to View and manipulate information about a session, such as the session identifier, creation time, and last accessed time Bind objects to sessions, allowing user information to persist across multiple user connections To Store and retrieve of attribute session.setAttribute(“cartItem”, cart) session.getAttribute(“cartItem”) All session data are kept on the server Only session ID sent to client CSIE33000 Network Programming Servelets 45 Sample HTTP Session public class SessionServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); OutputStream out = res.getOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out)); HttpSession session = req.getSession(false); if (session == null) { session=req.getSession(true); session.putValue("VisitCount", "1"); } pw.println("<html><body><pre>"); pw.println("session.isNew()=“ + session.isNew()); CSIE33000 Network Programming Servelets 46 Shiow-yang Wu Note 23
  24. 24. CSIE33000 Net Programming Lecture11 Java Servelet Sample HTTP Session pw.println("session.getCreationTime()=“ + new java.util.Date(session.getCreationTime())); pw.println("session.getID()=“ + session.getId()); pw.println("session.getLastAccessedTime()=" + new java.util.Date(session.getLastAccessedTime())); String strCount =(String) session.getValue("VisitCount"); pw.println("No. of times visited = " + strCount); int count = Integer.parseInt(strCount); count++; session.putValue("VisitCount", Integer.toString(count)); pw.println ("</pre></body></html>"); pw.flush(); } } CSIE33000 Network Programming Servelets 47 Session Timeout Used when an end-user can leave the browser without actively closing a session Session usually timeout after 30 minutes of inactivity Product specific A different timeout may be set getMaxInactiveInterval() setMaxInactiveInterval() CSIE33000 Network Programming Servelets 48 Shiow-yang Wu Note 24
  25. 25. CSIE33000 Net Programming Lecture11 Java Servelet Issues with “Stale” Session Objects The number of “stale” session objects that are in “to be timed out” could be large and affect system performance, for example, 1000 users with average 2 minutes session time, thus 15000 users during a period of 30 minutes 4K bytes of data per session 15000 sessions * 4K = 60M bytes of session data – just for one application CSIE33000 Network Programming Servelets 49 Session Invalidation Can be used by servlet programmer to end a session proactively by calling invalidate() When a user at the browser clicks on “logout” button When business logic ends a session Caution: a session object could be shared by multiple servlet/JSP-pages and invalidating it could destroy data that other servlet/JSP- pages are using CSIE33000 Network Programming Servelets 50 Shiow-yang Wu Note 25
  26. 26. CSIE33000 Net Programming Lecture11 Java Servelet HttpSession Methods Object getAttribute(String) – Value for the given name Enumeration getAttributeNames() - All the names of all attributes in the session long getCreationTime() - Time at which this session was created String getId() - Identifier assigned to this session long getLastAccessedTime() - Last time the client sent a request carrying the identifier assigned to the session int getMaxInactiveInterval() - Max time (in seconds) between requests that the session will be kept CSIE33000 Network Programming Servelets 51 HttpSession Methods ServletContext getServletContext() - ServletContext for session void invalidate() - Invalidates the session boolean isNew() - true if it has been created by the server (client has not yet acknowledged joining the session) void setAttribute(String, Object) - Sets the value for the given name void removeAttribute(String) - Removes the value for the given name void setMaxInactiveInterval(int) - Sets the maximum interval between requests CSIE33000 Network Programming Servelets 52 Shiow-yang Wu Note 26
  27. 27. CSIE33000 Net Programming Lecture11 Java Servelet Assignment 6 A simple e-commerce site To understand how server-side applications are designed To practice how to implement server-side applications using Java servlet To practice the handling of Web sessions Due: May 27, 2004 CSIE33000 Network Programming Servelets 53 Shiow-yang Wu Note 27