Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.

Similar presentations


Presentation on theme: "Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend."— Presentation transcript:

1 Servlets Compiled by Dr. Billy B. L. Lim

2 Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend the functionality of the Web server. Servlets can: –generate HTML dynamically to be returned to the client in response to some request –act as a communication gateway to other resources on the server, e.g. databases, other applications, etc.

3 Servlets (2) –coordinate connections from a number of clients –open a separate connection from the server to an applet on the browser using a "state-full" protocol, e.g. IIOP, RMI, TCP/IP –provide additional (customized) processing for the server's standard routines –filter data to be delivered to client applet

4 Servlets (3) Servlets are a superior solution over alternative technologies, e.g. CGI and server specific APIs: –Better performance (same address space); no, per request, process startup time –Written in Java -- better performance than scripting languages, e.g. PERL or Unix shell scripts –More portable (write-once run-on-any-server) –Stronger security model

5 Servlet Lifecycle The lifecycle of a servlet begins when it is loaded into a Web server and ends when it is terminated or is reloaded. When a servlet is loaded, the server creates an instance of the servlet and calls the servlet init() method. A servlet may be loaded: –automatically at server startup –at first client request –when a servlet is reloaded

6 Servlet Lifecycle (2) When a client request arrives at the server, the server creates a Request object and a Response object that are specific to that client request. The server then invokes the servlet's service() method, passing both the Request and Response objects as parameters. The servlet gets information about the request from the Request object, processes the request, and uses methods of the Response object to return a response to the client. The service() method may invoke other methods during the processing of the request, e.g. doGet(), doPost(), or additional methods you write. When the server no longer needs the servlet, the server invokes the servlet's destroy() method.

7 Servlets and Java SDK API The basic JavaServer API is provided in two Java packages, javax.servlet and javax.servlet.http. To create a servlet, extend javax.servlet.http.HttpServlet. (The HttpServlet class is a subclass of GenericServlet and has specialized methods for interacting with data transferred by the Web browser.) There are two methods for passing information to the server from the browser. –These methods, GET and POST, differ primarily in the manner in which the data is supplied. For the GET method, data is encoded and sent along as part of the URL. In the POST method, the data is also encoded but is supplied as a separate data "packet", not part of the URL.

8 Servlets and Java SDK API (2) The default behavior of the service() method of HttpServlet determines whether the information sent with the request is being provided by GET or POST. If the information is being provided by GET, the service() method invokes the doGet() method. If the information is being provided by POST, the service() method invokes the doPost() method.

9 HttpServletRequest Objects Provides access to HTTP header data (e.g., cookies found, HTTP method, arguments that the client sent as part of the request). To access client data: –The getParameter method returns the value of a named parameter. If your parameter could have more than one value, use getParameterValues instead. –The getParameterValues method returns an array of values for the named parameter. (The method getParameterNames provides the names of the parameters.)

10 HttpServletRequest Objects (2) –For HTTP GET requests, the getQueryString method returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values. –For HTTP POST, PUT, and DELETE requests, If you expect text data, the getReader method returns a BufferedReader for you to use to read the raw data. If you expect binary data, the getInputStream method returns a ServletInputStream for you to use to read the raw data

11 HttpServletResponse Objects An HttpServletResponse object provides two ways of returning data to the user: –The getWriter method returns a Writer Use the getWriter method to return text data to the user –The getOutputStream method returns a ServletOutputStream Use 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.

12 Handling GET and POST Requests To handle HTTP requests in a servlet, extend the HttpServlet class and override the servlet methods that handle the HTTP requests that your servlet supports. –Handling GET requests involves overriding the doGet method. –Handling POST requests involves overriding the doPost method.

13 Handling GET Request 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) { // and the information about the book and print it... } out.println(" "); out.close(); }... }

14 Handling POST Request 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(); }... }

15 Session Tracking Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. Sessions are shared among the servlets accessed by a client. This is convenient for applications made up of multiple servlets. To use session tracking, –Get a session (an HttpSession object) for a user. –Store or get data from the HttpSession object. –Invalidate the session (optional).

16 Obtaining a Session The getSession method of the HttpServletRequest object returns a user's session. When you call the method with its create argument as true, the implementation creates a session if necessary. To properly maintain the session, you must call getSession before any output is written to the response.

17 Storing/Getting Data from a Session The HttpSession interface provides methods that store and return: –Standard session properties, such as a session identifier –Application data, which is stored as a name- value pair, where the name is a String and the value is an object in the Java programming language. (This is like java.util.Dictionary.)

18 Storing/Getting Data from a Session (2) Because multiple servlets have access to a user's session, you should adopt a naming convention for organizing the names associated with application data. This avoids servlets accidentally overwriting each other's values in the session. One such convention is servletname.name where servletname is the full name of the servlet, including its packages (e.g., com.acme.WidgetServlet.state is a cookie with the servletname com.acme.WidgetServlet and the name state).

19 Tracking Session: Example public class CatalogServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getValue(session.getId()); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.putValue(session.getId(), cart); }... }

20 References Mary Campione, Kathy Walrath, The Java Tutorial Second Edition: Object-Oriented Programming for the Internet, Addison- Wesley, 1998. IBM Introduction to Servlets, Online tutorial, 1999.


Download ppt "Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend."

Similar presentations


Ads by Google