Java Servlets 02/09/20 1 Introduction Servlets are modules

Java Servlets 02/09/20 1 Introduction Servlets are modules

Java Servlets 02/09/20 1 Introduction Servlets are modules that extend request/response-oriented servers, such as Javaenabled web servers. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol. Servlets are portable. 02/09/20 2 Servlet Basics A servlet is an object of the javax.servlet class, which is not part of the JDK.

A servlet runs inside a Java Virtual Machine (JVM) on a server host. A servlet is an object. It is loaded and runs in an object called a servlet engine, or a servlet container. 02/09/20 3 The Servlet class The Servlet class is not part of the Java Development Kit (JDK). There are many packages that support servlets, including The JSWDK (Java Server Web Development Kit) the API documentation can also be downloaded from the same site freeware provided by Sun for demonstration of the technology, downloadable from http://java.sun.com/products/servlet/archive.htmlhttp://java.sun. com/products/servlet/download.html (link is in web sites section in course home page) we will use

this in our lab. The Tomcat : a free, open-source implementation of Java Servlet and JavaServer Pages technologies developed under the Jakarta project at the Apache Software Foundation. Application servers such as WebLogic, iPlanet, WebSphere. 02/09/20 4 Typical Uses for Servlets http://java.sun.com/docs/books/tutorial/servlets/overview/index.html Providing the functionalities of CGI scripts with a better API and enhanced capabilities. Allowing collaboration between people. A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as online conferencing. Forwarding requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers,

according to task type or organizational boundaries. 02/09/20 5 The architecture for servlet support s erv let1 c o d e S e rve r1 C lie n t1 s e r v le t2 c o d e C lie n t2 s e r v le t3 c o d e S e rve r2 s e r v le t e n g in e

o r s e r v le t c o n ta in e r C lie n t3 A s e r v le t c o n t a in e r o r s e r v le t e n g in e is r e q u ir e d . T h e s e r v le t e n g in e c a n b e p a r t o f a s e r v e r , o r a m o d u le e x te r n a l to a s e r v e r . 02/09/20 6 The Life Cycle of an HTTP Servlet The web server loads a servlet when it is called for in a web page. The web server invokes the init( ) method of the servlet. The servlet handles client responses. The server destroys the servlet (at the request of the system administrator). A servlet is normally not destroyed once it is loaded. 02/09/20

7 The Servlet Life Cycle http://java.sun.com/docs/books/tutorial/servlets/lifecycle/index.html s e r v le t e n g in e s erv let c o de S erver C lie n t s e r v e r lo a d s s e r v le t c o d e a n d in it ia liz e s a s e r v le t , p o s s ib ly a s a r e s u lt o f a c lie n t 's r e q u e s t s e r v le t e n g in e serv let c ode C lie n t S e rve r V ia t h e s e r v e r , t h e s e r v le t h a n d le s z e r o o r m o r e c lie n t r e q u e s t s

C lie n t s e r v le t e n g in e s erv let c o de S erver T h e s e r v e r r e m o v e s th e s e r v le t w h e n th e r e is n o m o r e c lie n t r e q u e s t fo r it. (s o m e s e r v e r s d o t h is s te p o n ly w h e n th e y s h u t d o w n ) 02/09/20 8 A simplified sequence diagram c lie n t 1 c lie n t2 s e r v le t

c o n ta in e r serve r lo a d s s e r v le t s e r v le t in it ( ) H TTP re qu e st s e r v ic e ( ) H TTP respon se H TTP requ est s e r v ic e ( ) H TTP re spon se te r m in a te de stro y ( )

shut down 02/09/20 9 The Servlet Interface S e r v le ts g e n e r ic s e r v le t s H T T P s e r v le t s " T h e c e n t r a l a b s tr a c tio n in t h e S e r v le t A P I is a S e r v le t in te r fa c e . A ll s e r v le ts im p le m e n t th is in te r fa c e e ith e r d ir e c tly o r , m o r e c o m m o n ly , b y e x te n d in g a c la s s th a t im p le m e n ts it s u c h a s H T T P S e r v le t T h e S e r v le t in te r f a c e d e c la r e s , b u t d o e s n o t im p le m e n t , m e t h o d s th a t m a n a g e

th e s e r v le t a n d its c o m m u n ic a tio n s w it h c lie n ts . S e r v le t w r it e r s p r o v id e s o m e o r a ll o f t h e s e m e t h o d s w h e n d e v e lo p in g a s e r v le t ." h t t p : //j a v a .s u n .c o m /d o c s /b o o k s /t u t o r i a l /s e r v l e t s / y o u r s e r v le t 02/09/20 10 Generic Servlets and HTTP Servlets Java Servlet Programming, OReilley Press Every servlet must implement the javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet: most general javax.servlet.http.HttpServlet: an extension of HTTP servers.

A generic servlet should override the service( ) method to process requests and generate appropriate responses. An HTTP servlet overrides the doPost( ) and/or doGet( ) method. 02/09/20 11 Generic and HTTP Servlets G e n e r ic S e r v le t C lie n t req u est S erv er resp o n se s e r v ic e ( )

H T T P S e r v le t B ro w ser req u est resp o n se H T T P S erver doG et ( ) s e r v ic e ( ) d o P o s t( ) 02/09/20 12 A simple Servlet, from http://java.sun.com/docs/books/tutorial/servlets/overview/simple.html public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println(""); out.println(title); out.println(""); out.println("

" + title + "

"); out.println("

This is output from SimpleServlet."); out.println(""); out.close(); } //end method } // end class 02/09/20 13 Using HTTP Servlet to process web forms http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html

Requests and Responses Methods in the HttpServlet class that handle client requests take two arguments: An HttpServletRequest object, which encapsulates the data from the client An HttpServletResponse object, which encapsulates the response to the client The methods for handling HTTP requests and responses are: public void doGet (HttpServletRequest request, HttpServletResponse response) for requests sent using the GET method. public void doPost(HttpServletRequest request, HttpServletResponse response) for requests sent using the POST method. 02/09/20 14

HttpServletRequest Objects http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. allows you to obtain the arguments that the client sent as part of the request. To access client data sent with an HTTP request: The getQueryString method returns the query string. The getParameter method returns the value of a named parameter. The getParameterValues method returns an array of values for the named parameter. 02/09/20 15

HttpServletRequest Interface public String ServletRequest.getQueryString( ); returns the query string of the reequst. public String GetParameter(String name): given the name of a parameter in the query string of the request, this method returns the value. String id = GetParameter(id) public String[ ] GetParameterValues(String name): returns multiple values for the named parameter use for parameters which may have multiple values, such as from checkboxes. String[ ] colors = req.getParmeterValues(color); if (colors != null) for (int I = 0; I < colors.length; I++ ) out.println(colors[I]); public Enumeration getParameterNames( ): returns an enumeration object with a list of all of the parameter names in the query string of the request. 02/09/20 16 HttpServletResponse Objects

http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html An HttpServletResponse object provides two ways of returning data to the user: The getWriter method returns a Writer The getOutputStream method returns a ServletOutputStream Use the getWriter method to return text data to the user, and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete. 02/09/20 17 HttpServletResponse Interface public interface HttpServletResponse extends ServletResponse: The servlet engine provides an object

that implements this interface and passes it into the servlet through the service method Java Server Programming public void setContentType(String type) : this method must be called to generate the first line of the HTTP response: setContentType(text/html); public PrintWriter getWriter( ) throws IOException: returns an object which can be used for writing the responses, one line at a time: PrintWriter out = res.getWriter; out.println(

Hello world

); 02/09/20 18 Servlets are Concurrent http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html HTTP servlets are typically capable of serving multiple clients concurrently: the servlet engine uses a separate thread to invoke each method.

Hence servlet methods should be thread-safe: If the methods in your servlet do work for clients by accessing a shared resource, then you must either: Synchronize access to that resource, or Ensure that the servlet can handle only one client request at a time (by using semaphores or locks). 02/09/20 19 Handling GET requests http://java.sun.com/docs/books/tutorial/servlets/client-interaction/httpmethods.html public class BookDetailServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content-type header before accessing the Writer response.setContentType("text/html");

PrintWriter out = response.getWriter(); // then write the response out.println("" + "Book Description" + ... ); //Get the identifier of the book to display String bookId = request.getParameter("bookId"); if (bookId != null) { // fetch the information about the book and print it out.println(""); out.close(); 02/09/20 } ... } ...} 20

Handling POST Requests http://java.sun.com/docs/books/tutorial/servlets/client-interaction/httpmethods.html public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter( ); // then write the response out.println("" + " Receipt " + ...); out.println("Thank you for purchasing your books from us " + request.getParameter("cardname") + ...); out.close(); } ... } 02/09/20

21 Session State Information The mechanisms for state information maintenance with CGI can also be used for servlets: hidden-tag, URL suffix, file/database, cookies. In addition, a session tracking mechanism is provided, using an HttpSession object. 02/09/20 22 Cookies in Java http://java.sun.com/products/servlet/2.2/javadoc/index.html A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.

The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servelet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies( ) method. Several cookies might have the same name but different path attributes. 02/09/20 23 Processing Cookies with Java Java Server Programming Wrox press A cookie is an object of the javax.servlet.http.cookie class. Methods to use with a cookie object: public Cookie(String name, String value): creates a cookie with the name-value pair in the arguments.

import javax.servlet.http.* Cookie oreo = new Cookie(id,12345); public string getName( ) : returns the name of the cookie public string getValue( ) : returns the value of the cookie public void setValue(String _val) : sets the value of the cookie public void setMaxAge(int expiry) : sets the maximum age of the cookie in seconds. 02/09/20 24 Processing Cookies with Java 2 Java Server Programming Wrox press public void setPath(java.lang.String uri) : Specifies a path for the cookie to which the client should return the cookie. The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, which makes the cookie visible to all directories on the server under /catalog. public java.lang.String getPath() : Returns the path on the

server to which the browser returns this cookie. The cookie is visible to all subpaths on the server. public String getDomain( ) : returns the domain of the cookie. if orea.getDomain.equals(.foo.com) // do something related to golf public void setDomain(String _domain): sets the cookies domain. 02/09/20 25 doGet/doPost Method using cookies Public void doGet(HttpServletResponse req, HttpServletResponse res) throws ServletException, IOExceiption{ res.setContentType(text/html); PrintWriter out = res.getWriter( ); out.println (

Contents of your shopping cart:

); Cookie cookies[ ]; cookies = req.getCookies( ); if (cookies != null) {

for ( int i = 0; i < cookies.length; i++ ) { if (cookies[i].getName( ).startWith(Item)) out.println( cookies[i].getName( ) + : + cookies[i].getValue( )); out.close( ); } 02/09/20 26 HTTP Session Objects http://java.sun.com/products/servlet/2.2/javadoc/index.html The javax.servlet.http package provides a public interface HttpSession: Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the

user. A session usually corresponds to one user, who may visit a site many times. 02/09/20 27 HTTP Session Object - 2 http://java.sun.com/products/servlet/2.2/javadoc/index.html This interface allows servlets 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 Session object allows session state information to be maintained without depending on the use of cookies (which can be disabled by a browser user.) Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

02/09/20 28 The Session object Server ho st A S e s s io n o b je c t s e rve le t e n g in e s e r v le t C lient ho st w e b se rve r r e q u e st /r e sp o n se 02/09/20 29 Obtaining an HTTPSession Object

A session object is obtained using the getSession( ) method of the HttpServletRequest object (from doPost or doGet) public HTTPSession getSession(boolean create): Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null. To make sure the session is properly maintained, you must call this method before the response is committed. public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletRespnse res) throws ServletException, IOException // get session object HttpSession session = req.getSession(true) if (session != null) { } 02/09/20

30 The HTTPSession Object public java.lang.String getId( ): returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent. public java.lang.Object getAttribute(java.lang.String name): returns the object bound with the specified name in this session, or null if no object is bound under the name. public java.util.Enumeration getAttributeNames( ): returns an Enumeration of String objects containing the names of all the objects bound to this session. public void removeAttribute(java.lang.String name): removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing. 02/09/20

31 Session Object example based on an example in Java Server Programming, Wrox Press // Get item count from session object Integer itemCount = (Integer)session.getAttribute(itemCount); // if this is the first call during the session, no attribute exists if (itemCount == null) { itemCount = new Integer(0); // process form data String[ ] itemSelected; String itemName; itemSelected = req.getParameterValues(item); // if user has selected items on form, add them to the session object if (itemSelected != null) { for ( int i=0; i < itemSelected.length; i ++) { itemName = itemSelected[I]; itemCount = new Integer(itemCount.intValue( ) +1); session.setAttribue(Item + itemCount, itemName); }// end for

session.setAttribtue(itemCount, itemCount); } // end if 02/09/20 32 Session object example - continued PrintWriter out = res.getWriter( ); res.setContentType(text/html); // output HTML for web page heading // Output current contents of the shopping cart out.println(

Current Shopping Cart Contents

); for (int i = 1; i <= ItemCount.intValue( ); i++) ( // retrieve objects from the session object String item = (String) session.getAttribute(Item + i); out.println(item
); } // output HTML for web page footing out.close( ); 02/09/20

33

Recently Viewed Presentations

  • Paediatric cardiothoracic CTA - Learning - Home

    Paediatric cardiothoracic CTA - Learning - Home

    Paediatric cardiothoracic CTA. Indications, Technique. And Relevant Anatomy. Gerhard van derWesthuizen. Medical officer, Radiology. 3 Military hospital. 12 October 2012. Introduction. MDCT has revolutionised angiographic evaluation of the heart and thoracic vessels.
  • Introduction to Spark  MapReduce enables big data analytics

    Introduction to Spark MapReduce enables big data analytics

    Spark Core: is the execution engine for the spark platform. It provides distributed in-memory computing capabilities. Spark SQL: is an engine for Hadoop Hive that enables unmodified Hadoop Hive queries to run up to 100x faster on existing deployments and...
  • Lecture 3 John Woodward Copying Numbers int luckyNumber

    Lecture 3 John Woodward Copying Numbers int luckyNumber

    Author: John R Woodward Created Date: 09/08/2013 02:40:39 Title: PowerPoint Presentation Last modified by: John R Woodward
  • Injuries to the Patella and Extensor Mechanism

    Injuries to the Patella and Extensor Mechanism

    The ultimate goals are to preserve and/or restore extensor mechanism function and reduce complications of this articular fracture. Nonoperative treatment is indicated for nondisplaced fractures with an intact extensor mechanism, fractures with less than 2mm of articular step off and...
  • Introduction to Rhetoric Mr. Bui - English 11

    Introduction to Rhetoric Mr. Bui - English 11

    SOAPSTone. Speaker - the person delivering/addressing the message/subject. O. ccasion - the context that prompted the message. A. udience - the person/people to whom the message is directed. P. urpose - the intent of the speaker
  • From the mouth of the examiner…

    From the mouth of the examiner…

    Eventually the two were reconciled and Robert was recognised as William's heir for Normandy. However, Robert was not content with just being made heir to Normandy and when William died he claimed the throne of England as well, thus contributing...
  • mmmmm - metcalfe.k12.ky.us

    mmmmm - metcalfe.k12.ky.us

    The ester linkage is a covalent bond. ... Proteins- suffix "lin" eg insulin. Contain: C, H, O, N, P, and S. Protein monomers are known as amino acids, which then fold into the polypeptide form of proteins. ... mmmmm Last...
  • Headline goes here Second line - Aqua-Tech Sales and ...

    Headline goes here Second line - Aqua-Tech Sales and ...

    Two simple parts. The ecocirc® wireless kit Part #6050B4000 includes two parts, both certified for use with drinking water:. A lead-free . recirculation pump. at your hot water source . A battery-operated . mixing valve, with temperature sensor and transceiver,...