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/responseoriented servers, such as Java-enabled web servers. A servlet is a program invoked at runtime in the server side. Unlike applets, servlets have no graphical user interface. 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 Common Gateway Interface (CGI) CGI programs are capable to create dynamic web pages. A CGI program can be written in different languages , such as Perl and shell scripts. Server creates a new process for each clients request to run a CGI program. FastCGI creates a single persistent process for many FastCGI programs. A CGI program cannot interact with the web server, such as writing to servers log file. FastCGI allows programs to interact with the web server, such as reading a file, before the request is handed over. 02/09/20 3

Servlet Basics A servlet is an object of the javax.servlet class. Unlike applets, servlets do not require special support in the web browser. The Servlet class is not part of the Java Development Kit (JDK). A servlet is an object. It is loaded and runs in a servlet engine, or servlet container, such as Apache Tomcat . 02/09/20 4 Uses for Servlets

Providing the functionalities of CGI scripts with a better API and enhanced capabilities. Allowing collaboration: A servlet can handle multiple requests concurrently, and can synchronize requests. Forwarding requests: Servlets can forward requests to other servers and servlets. Servlets can be used to balance load among several servers that mirror the same content partition a single logical service over several servers, according to task type or organizational boundaries. 02/09/20 5 Generic Servlets and HTTP Servlets Java Servlet Programming, OReilley Press

Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet javax.servlet.http.HttpServlet, which extends GenericServlet. A generic servlet should override the service( ) method to process requests and generate appropriate responses. An HTTP servlet overrides the doPost( ), doGet( ) or service( ) method. 02/09/20 6 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 7 A simple Servlet 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(); } } 02/09/20 8 Using HTTP Servlet to process web forms 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 E.g., public void doGet (HttpServletRequest request, HttpServletResponse response) public void doPost(HttpServletRequest request, HttpServletResponse response) 02/09/20 9 HttpServletRequest Objects An HttpServletRequest object provides access to HTTP header data, such as any cookies, and the HTTP method. The HttpServletRequest object allows you to obtain the

arguments that the client sent as part of the request. getParameter () returns the value of a named parameter getParameterValues() returns an array of values for the named parameters. getParameterNames() provides the names of the parameters. For HTTP GET requests, the getQueryString() returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values. Ref: req-res.html 02/09/20 10 HttpServletRequest Interface public String ServletRequest.getQueryString( ); returns the query string of the request. 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 11 HttpServletResponse Objects

An HttpServletResponse object provides two ways of returning data to the user: The getWriter () returns a Writer (for text data) The getOutputStream () returns a ServletOutputStream (for binary data) Closing the Writer or ServletOutputStream after sending the response allows the server to know when the response is complete. Ref: 02/09/20 12 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 13 Servlets are Concurrent servers HTTP servlets are typically capable of serving

multiple clients concurrently. If the methods in a servlet do work for clients by accessing a shared resource, then you must either: Synchronize access to that resource, or Create a servlet that handles only one client request at a time. 02/09/20 14 Handling GET requests 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

} ...} 15 Handling POST Requests 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 16 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 17 Servlet Examples a simple servlet illustrates that a servlet is persistent illustrates the use of synchronized method with a servlet GetForm.html, illustrates the processing of data sent with an HTTP request via the GET method PostForm.html, illustrates the processing of data sent with an HTTP request via the POST method Ref:

02/09/20 18 Session State Information The mechanisms for state information maintenance with CGI can also be used for servlets: hidden-tag URL suffix file/database HTTP Cookies HttpSession object 02/09/20 19

Cookies in Java HTTP Cookie (session/persistent) is a message given to a web browser by a web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server. The main purpose of cookies is to identify users and possibly prepare customized Web pages for them. A cookie has: a name and a value optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. 02/09/20

20 Cookies in Java The servlet sends cookies to the browser by using the HttpServletResponse.addCookie() method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. 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 21

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

22 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(

// do something related to golf public void setDomain(String _domain): sets the cookies domain. 02/09/20 23 doGet 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 24 Servlet & Cookies Example Cart.html: web page to allow selection of items Servlet invoked by Cart.html; it instantiates a cookie object for each items selected. Cart2.html: web page to allow viewing of items currently in cart Servlet to scan cookies received with the HTTP request and display the contents of each cookie. Ref: 02/09/20

25 / HTTP Session Objects The javax.servlet.http package provides a public interface HttpSession: identify a user 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 26 HTTP Session Object - 2 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 27 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 28 Obtaining an HTTPSession Object Obtain an HttpSession Object public HTTPSession getSession(boolean create): returns the current HttpSession associated with this request or, 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, this method must be called 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 29 The HTTPSession Object methods HTTPSession methods: 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. public void putValue(java.lang.String name, java.lang.Object value) public void setAttribute(java.lang.String name, java.lang.Object value) 02/09/20 30 Session Object example Cart.html: web page to allow selection of items Servlet invoked by Cart.html; it instantiates a

session object which contains descriptions of items selected. Cart2.html: web page to allow viewing of items currently in cart Servlet to display items in the shopping cart, as recorded by the use a session object in the Cart servlet Ref: 02/09/20 31 Summary - 1 A servlet is a Java class. Its code is loaded to a servlet container on the server host. It is initiated by the server in response to a clients request.

Once loaded, a servlet is persistent. 02/09/20 32 Summary - 2 For state information maintenance: hidden form fields cookies the servlets instance variables may hold global data a session object can be used to hold session data 02/09/20 33

Recently Viewed Presentations

  • Islam Masa Khulafaur Rashidin

    Islam Masa Khulafaur Rashidin

    Penyebaran Islam. Abu Bakar mengirim kekuatan ke luar Arabia, yaitu wilayah-wilayah kekuasaan Bizantium. Misalnya, Khalid bin Walid dikirim ke Iraq dan dapat menguasai al-Hirah pada tahun 634 M. Sementara itu, ke Syria dikirim ekspedisi di bawah pimpinan empat jenderal, yaitu...
  • Chapter 9 Buffer Zones and Posting Requirements

    Chapter 9 Buffer Zones and Posting Requirements

    TEMPERATURE INVERSIONS. Temperature inversion conditions typically start an hour before sunset and continue past sunrise. They may persist as late as noontime. However, inversions can persist all day long. Inversion conditions are . common on nights with . limited cloud...
  • Real-Time Image Mosaicing

    Real-Time Image Mosaicing

    Real-Time Image Mosaicing--Research Project for 15-869, Nov 29, 1999 Li Zhang Image Mosaicing Stitching together images taken from different viewpoints seamlessly Representation: cylindrical, spherical, and perspective panoramas Problem Statement Given two images I0 and I1 of a scene, find a...
  • Equivalent Fractions

    Equivalent Fractions

    Equivalent fractions are fractions that name the same amount. 2 4 = 4 8 Multiply the numerator and denominator by the same number. Divide the numerator and denominator by the same number (it has to be a common factor to...
  • Creating a New Work Book - Socorro Independent School District

    Creating a New Work Book - Socorro Independent School District

    pixels (8.43 characters equals 64 pixels) Note: Pixel size is based on screen resolution. Row height. Measured in . points (1/72 of an inch) or pixels. Default row height: 15 points or 20 pixels. New Perspectives on Microsoft Office 2013....
  • PowerPoint-Präsentation


    Write five facts about pre-history (the reading guide ya'll did yesterday. Be sure you have five by the time I am done with roll. P. R. E. H. I. S. T. O. R. Y
  • Austin Comerton Manager, Business Development 1 877

    Austin Comerton Manager, Business Development [email protected] 1 877

    Several satellites pick up a call, and this "path diversity" reduces the possibility of blocked or dropped calls. If buildings or terrain obstruct the phone's line-of-sight to a satellite, a "soft hand-off" takes place switching the call to an alternate...
  • ARVs & DDIs in pregnancy Dr. Angela Colbers,

    ARVs & DDIs in pregnancy Dr. Angela Colbers,

    RTV boosted (DRV/RTV QD) AUC total 34-35%. AUC unbound 20-34%. AUC DRV total 50-56%. AUC DRV unbound 40-55%. Poster: Mark . Mirochnick presents data from P1026 (IMPAACT) Hier beginnen met: Naast de bekende en vanzelfsprekende veranderingen die elke zwangere vrouw...