Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial

Similar presentations


Presentation on theme: "COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial"— Presentation transcript:

1 COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Intro.html

2 COMP201 Topic 14 / Slide 2 Objective & Outline l Objective: Introduction to servlets l Outline: n Introduction n A simple servlet –Environment for developing and testing servlets n General information about servlets n HTTP Servlets n Session tracking n Cookies

3 COMP201 Topic 14 / Slide 3 Resources l Book: Marty Hall, Core SERVLETS and JAVA SERVER PAGES, A Sun Microsystems Press/Prentice Hall PTR Book. ISBN 0-13-089340-4 n Available online: http://pdf.coreservlets.com/ l Online tutorials n Servlets and JavaServer Pages (JSP) 1.0: A Tutorial http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Intro.html http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Intro.html n The J2EE Tutorial: http://java.sun.com/j2ee/tutorial/http://java.sun.com/j2ee/tutorial/ l Apache Tomcat Software: n Standalone web server for servlet and JSP development n Download: http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/ n Installation: http://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.html l Servlet API: http://java.sun.com/products/servlet/2.3/javadoc/index.html

4 COMP201 Topic 14 / Slide 4 Introduction l Servlets are programs that run on server n Acting as a middle layer between client requests and databases or other applications. l Example: Duke’ Book store: http://monkey.cs.ust.hk:8080/bookstore.html

5 COMP201 Topic 14 / Slide 5 Introduction l Traditionally, HTTP servers handle client requests by using CGI (common gateway interface) scripts. 1. User fills out a form and submit. 2. HTTP server gets URL requests from the net. 3. HTTP server finds the CGI script specified in the HTML file, runs it with parameters from requesting URL 4. HTTP server takes output from the CGI program (most often output is HTML text), fixes it up with a full complete HTTP header, and sends it back to the original requesting client HTML: First Name: Last Name:

6 COMP201 Topic 14 / Slide 6 Introduction l Advantages of servlets over CGI scripts (Hall book) n More efficient n Easier to use n More powerful. n More portable n Safer l Note: n CGI scripts written in scripting languages such as Perl, Python, Unix Shell, etc doe not need compilation. n CGI scripts written in programming languages such as C, C++ need compilation n Servlets need compilation

7 COMP201 Topic 14 / Slide 7 Servlet vs. Applet l Servlets are to servers what applets are to browsers: l Applets run by browser, servlets run by server. l Applets are “client-side java”, servlets are “server-side java”. l Applets makes appearance of web pages alive, servlets makes contents of web pages dynamic. l Unlike applets, however, servlets have no graphical user interface. Implement only back-end processing.

8 COMP201 Topic 14 / Slide 8 Outline l Introduction l A simple servlet n Environment for developing and testing servlets l General information about servlets l HTTP Servlets l Session tracking l Cookies

9 COMP201 Topic 14 / Slide 9 A Simple Servlet import java.io.*; import javax.servlet.*; public class SimpleGenericServlet extends GenericServlet { public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Hello World"); out.close(); } Note: no main method. Servlet run by server, just as applet run by browser

10 COMP201 Topic 14 / Slide 10 A Simple Servlet service : The most important method in a servlet, Determines what the servlet does. Invoked automatically when a request comes in. Needs to be overridden. l It takes two arguments: service (ServletRequest request, ServletResponse response) ServletRequest and ServletResponse are interfaces defined by the javax.servlet Get information about a request from the ServletRequest object request. Set information about a response via the ServletResponse object response. l GenericServlets uncommon. So we don’t study those in details

11 COMP201 Topic 14 / Slide 11 Environment for developing and testing servlets l Compile: n Need Servlet.jar. Available in Tomcat package l Setup testing environment n Install and start Tomcat web server n Place compiled servlet at appropriate location –See http://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.html l Run example: n http://monkey.cs.ust.hk:8080/servlet/SimpleGenericServlet

12 COMP201 Topic 14 / Slide 12 Outline l Introduction l A simple servlet n Environment for developing and testing servlets l General information about servlets l HTTP Servlets l Session tracking l Cookies

13 COMP201 Topic 14 / Slide 13 General Information about Servlets Architecture of package javax.servlet Servlet interface: declares servlet methods ( init, service, etc.) GenericServlet implements Servlet HttpServlet subclass adds features specific to HTTP Technically, a servlet is a program that extends either GenericServlet or HttpServlet.

14 COMP201 Topic 14 / Slide 14 General Information about Servlets Servlet Life Cycle l Servlets are controlled by servers 1. A server loads and initializes the servlet l New thread created for each client. 2. The servlet handles zero or more client requests 3. The server terminates the servlet

15 COMP201 Topic 14 / Slide 15 Servlet Life Cycle l Methods public void init(): Called only once when servlet is being created. Good place for set up, open Database, etc. public void service(): Called once for each request. In HttpServlet, it delegates requests to doGet, doPost, etc. l public void destroy(): Called when server decides to terminate the servlet. Release resources.

16 COMP201 Topic 14 / Slide 16 Outline l Introduction l A simple servlet n Environment for developing and testing servlets l General information about servlets l HTTP Servlets l Session tracking l Cookies

17 COMP201 Topic 14 / Slide 17 HTTP Servlets l For HTTP requests. l HTTP requests include l GET, conditional GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS l The default is GET.

18 COMP201 Topic 14 / Slide 18 HTTP Servlets Methods of HttpServlet and HTTP requests All methods take two arguments: an HttpServletRequest object and an HttpServletResponse object. Return a BAD_REQUEST (400) error by default. MethodsHTTP RequestsComments doGet GET, HEADUsually overridden doPost POSTUsually overridden doPut PUTUsually not overridden doOptions OPTIONSAlmost never overridden doTrace TRACEAlmost never overridden

19 COMP201 Topic 14 / Slide 19 HTTP Servlets javax.servlet.http.HttpServlet l subclass of GenericServelt, hence has service method class has already overridden the service method to delegate requests to special purpose methods such as doGet and doPost. Don’t override the service method when sub classing HttpServlet. Instead, refine the special purpose methods, mostly doGet and doPost.

20 COMP201 Topic 14 / Slide 20 javax.servlet.http. HttpServletRequest Objects l Extends the ServletRequestServletRequest l Provide access to HTTP header data and the arguments of the request. l Can get values of individual parameters using the following methods getParameterNames method provides the names of the parameters getParameter method returns the value of a named parameter. getParameterValues method returns an array of all values of a parameter if it has more than one values. HTTP Servlets

21 COMP201 Topic 14 / Slide 21 HttpServletResponse Objects l Provide two ways of returning data to the user: getWriter method returns a PrintWriter for sending text data to client getOutputStream method returns a ServletOutputStream for sending binary data to client. Need to close the Writer or ServletOutputStream after you send the response. l HTTP Header Data Must set HTTP header data before you access the Writer or OutputStream. HttpServletResponse interface provides methods to manipulate the header data. For example, the setContentType method sets the content type. (This header is often the only one manually set.) HTTP Servlets

22 Handling GET requests : Override the doGet method 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(); out.println(...); // then write the response //Get the identifier of the book from request String bookId = request.getParameter("bookId"); if (bookId != null) { out.println( information about the book );} out.close(); …… Try getRequest.html and getRequest2.html on http://monkey.cs.ust.hk:8080/201html/index.html BookDetailServlet.java in bookstore example

23 Handling POST requests: Override the doGPost method 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(); out.println(...); // then write the response out.println(" Thank you for … " + request.getParameter("cardname") +...); out.close(); } Try postRequest.html ReceiptServlet.java in bookstore example

24 COMP201 Topic 14 / Slide 24 l Handling both GET and POST requests in the same way public class BookDetailServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // codes for handling the request } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet( request, response); } HTTP Servlets

25 COMP201 Topic 14 / Slide 25 Outline l Introduction l A simple servlet n Environment for developing and testing servlets l General information about servlets l HTTP Servlets l Session tracking l Cookies

26 COMP201 Topic 14 / Slide 26 Session Tracking l Servlets in Duke’s Bookstore n BookStoreServlet: Forward to main page n CatalogServlet: Show all books and allow selection n BookDetailServlet: Show details of a book and allow selection n ShowCartServlet: Show shopping cart n CashierServlet: Check out

27 COMP201 Topic 14 / Slide 27 Session Tracking Motivation In the Duke’s Bookstore example, suppose a client has selected several books. (Do this and check the page produced by CatalogServlet.) l Problem 1: l The client requests ShowCartServlet to show the books in his/her shopping cart. l Question: How does ShowCartServlet know the selected books? l How communications between servlets are facilitated? l Problem 2: l The client decides to leave the bookstore and visit some other pages. l Question: When the client comes back and makes further requests, how do the servlets know the books that have been selected previously? l How come servlets can remember things?

28 COMP201 Topic 14 / Slide 28 Session Tracking l Session tracking is a mechanism that servlets use to maintain state about a series of requests l From the same user (that is, requests originating from the same browser) l Across some period of time Solution to Problem 2: Servlets use sessions as “notebook” and hence can remember l Sessions are shared among the servlets accessed by the same client. Solution to Problem 1. Servlets communicate via sessions.

29 COMP201 Topic 14 / Slide 29 Session Tracking l Session is associated with a request. l To use session, n Get session from HttpServletRequest request: –HttpSession getSession(boolean create) –HttpSession mySession = request.getSession(boolean create); –Case 1: create==true l Return the associated session if exists l Otherwise, create a new session, associate it with the request, and return the session –Case 2: create==false l Return the associated session if exists l Otherwise, return null. –Note: get session before accessing response streams.

30 COMP201 Topic 14 / Slide 30 Session Tracking Store/retrieve information to/from HttpSession object. public void setAttribute(String name, Object obj) public Object getAttribute(String name). n Invalidate the session (optional). –Manually: Session.invalidate() –Automatically when no request after certain time. l void setMaxInactiveInterval(int interval) n Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout.

31 public class HelloAgainServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); HttpSession session = req.getSession(true); // get session if exists, does not create PrintWriter out = resp.getWriter(); out.println(" Count me! "); name = req.getParameter("name"); if (session == null) {out.println("Welcome," + name + ", I don't believe we've met!"); session = req.getSession(true); // create session session.setAttribute("Count", new Integer(1)); } else {int n=((Integer)session.getAttribute("Count")).intValue(); out.println("You again? " + name); out.println("That makes " + (n + 1) + " visits!"); session.setAttribute("Count", new Integer(n + 1)); } out.println(" "); out.close(); } private String name = ""; } http://monkey.cs.ust.hk:8080/servlet/HelloAgainServlet?name=Nevin HelloAgainServlet.java

32 COMP201 Topic 14 / Slide 32 Session Tracking l The program presented on the previous slide has a bug. l The fix is to change n HttpSession session = req.getSession(true); to n HttpSession session = req.getSession(false); l Some interesting observations: n After you test the correct version, go back and test the original version. It works! Why?

33 COMP201 Topic 14 / Slide 33 Session Tracking l Session tracking in Duke’s Bookstore n Discussion the following in class –CatalogServlet.java –ShowCartServlet.java

34 COMP201 Topic 14 / Slide 34 Outline l Introduction l A simple servlet n Environment for developing and testing servlets l General information about servlets l HTTP Servlets l Session tracking l Cookies

35 COMP201 Topic 14 / Slide 35 Cookies l Cookies: objects containing a little bit information n Made at server n Sent to client for storage n Retrieved by server when client connects again n (Part of HTTP, supported by Java) l Cookies can be used for n Session tracking. HttpSession implemented using cookies. n Persistent state. E.g. name, address, email address. When user access some servlets again, no need to provide such information one more time.

36 COMP201 Topic 14 / Slide 36 Cookies l Details: n Each cookie is a name=value pair. n Servlets –create cookies and –send them to clients by adding fields to HTTP response headers. –Client browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. n Clients –automatically return cookies by adding fields to HTTP request headers. –cookies can be retrieved from the request headers n NOTE: Cookies shared among servlets on the server accessed by the same client.

37 COMP201 Topic 14 / Slide 37 Cookies Cookies are objects of class javax.servlet.http.Cookie l To send a cookie, 1. Create a Cookie object Cookie c = new Cookie(name, value); 2. Set attributes if necessary c.setMaxAge(30); // expire after 30 seconds 3. Send the cookie response.addCookie(c); l To get information from a cookie, 1. Retrieve all the cookies from the user's request Cookie[] cookies = request.getCookies(); 2. Find the cookie that you are interested in and get its value for (int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); }

38 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Cookies received from client: "); Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value + " "); } out.println(" Cookies sent to client:> "); String name = request.getParameter("cookieName"); if (name != null && name.length() > 0) { String value = request.getParameter("cookieValue"); Cookie c = new Cookie(name, value); c.setMaxAge(180); response.addCookie(c); out.println(name + " = " + value + " "); }} // CookieServlet.java

39 COMP201 Topic 14 / Slide 39 Cookies l Cookies not shared between different clients accessing the same server. n Try to Access the following from two different browsers http://monkey.cs.ust.hk:8080/servlet/CookieServlet?cookieName=cookie 1&cookieValue=a1 l Cookies are not shared between different servers accessed by the same client n Try: http://monkey.cs.ust.hk:8080/servlet/CookieServlet?cookieName=m onkey&cookieValue=a http://scpu8.cs.ust.hk:8080/servlet/CookieServlet?cookieName=scp u8&cookieValue=a


Download ppt "COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial"

Similar presentations


Ads by Google