CS4273: Distributed System Technologies and Programming I Lecture 9: Java Servlets.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Java Server Pages (JSP)
Java Servlets Java Server Pages (JSP)
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Servlets. Introduction Networking –Massive, complex topic –Java networking in several packages java.net –Socket based communications View networking as.
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.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
HTTP HyperText Transfer Protocol Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Java Servlets and Java Server Pages Carol Wolf Computer Science.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
 2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Java Servlets Java Server Pages (JSP)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
How CGI and Java Servlets are Run By David Stein 14 November 2006.
April 20023CSG11 Electronic Commerce Java (2) John Wordsworth Department of Computer Science The University of Reading Room 129,
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Servlets Outline 1 Introduction 2 Servlet Overview and Architecture 2.1 Interface Servlet and the Servlet Life Cycle 2.2 HttpServlet Class 2.3 HttpServletRequest.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Introduction to Servlets
Servlets.
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
JDBC & Servlet CSE 4504/6504 Lab.
Servlet.
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CS4273: Distributed System Technologies and Programming I Lecture 9: Java Servlets

2 CSlab Setting of Java Servlet Servlet Engine searches files in directory “/usr/local/jt/webapps”. To facilitate access to each person’s files, CSlab has made a link: ln -s /home/lec/jia/www/java/js /usr/local/jt/webapps/jia “/usr/jt/webapps/jia/”  “~jia/www/java/js/” 1.The servlet engine searches files relative from directory: /usr/local/jt/webapps/ is mapped to: “~jia/www/java/js/” + “WEB-INF/classes/” + XXX, because:  /usr/local/jt/webapps/jia  ~jia/www/java/js/ servlet  /WEB-INF/classes 2.All servlet *.class files MUST be in directory: ~jia/www/java/js/WEB-INF/classes/ The corresponding URL is: 3.All.html files MUST be in directory: ~jia/www/java/js/html/ The corresponding URL is:

3 Your personal directory setting 1.CSlab already made a link from /usr/jt/webapps/ to your personal directory “~501234/www/java/js” in CSlab account ( is your student number). 2.A copy of all sample programs is in /public/cs4273.tar (zipped at ~jia/www). You can un-zip all files into your directory “~501234/www/” by UNIX commands:  cd www// change dir to  tar –xvf /public/cs4273.tar// un-zip files into “~501234/www/java/js” 3.All files are in directories “www/java/js/WEB-INF/classes/”, “www/java/js/html/”. 4.To run servlet in “~501234/www/java/js/WEB-INF/classes/GetServlet.class”, URL is: To run a servlet by a html file in “~501234/www/java/js/html/test.html”, URL is: Note: 1) servEngine cannot detect any change of your program until it restarts. In current setting, servEngine auto-restarts every 20 min. Wait for about 20 min to refresh a page. 2) For each servlet, you need to add a new item in file …/js/WEB-INF/web.xml

4 Java Servlet Servlet runs on the web site. To enable servlets, it needs to install a servlet engine (e.g., Jserv, or Tomcat), which is a module of a web-server and runs inside the web-server process. Servlet replaces CGI program to link clients (in browser) to back-end servers. Servlet generates HTML pages, sent back to browser for display, similar to ASP. Servlet can support many protocols of request / response type, such as HTTP, URL, FTP, SMTP. That’s, any requests coming in the form of these protocols can be processed by a servlet (Servlet API defines the support of these protocols). The most common protocol that Servlet supports is HTTP.

5 Servlet Life Cycle Servlets run on the web server as part of the web-server process. The web-server initializes, invokes and destroys servlet instances. It invokes servlets via Servlet interface, consisting of three methods: init(). It is called only once, when the servlet is first loaded. It is guaranteed to finish before any other calls are made to the servlet. service(). Each request from a client results in a single call to this method. It receives (from the web server) a ServletRequest object & a ServletResponse object to get request / send reply to clients. destroy(). It is called to allow your servlet to clean up any resources. Most of the time, it is an empty method.

6 A Simple Servlet import javax.servlet.*; public class GenericServlet implements Servlet{ private ServletConfig config; public void init (ServletConfig config) throws ServletException { this.config = config; } public void destroy() {} // do nothing public ServletConfig getServletConfig() { return config; } public String getServletInfo() { return “A Simple Servlet”; } public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType( “text/html” ); PrintWriter out = res.getWriter(); out.println( “ ” ); out.println( “ A Simple Servlet ” ); out.println( “ ” ); out.println( “ Hello Servlet ” ); ………… out.close(); } }

7 Http Servlet The servlet package has two abstract classes that implement interface Servlet: GenericServlet from package javax.servlet HttpServlet from package javax.servlet.http HttpServlet overrides the key method service() by adding the code to distinguish HTTP requests and invokes corresponding methods: –doPost() –doGet() –doHead() –doDelete() –doOption() –doTrace() Most of programs extend class HttpServlet, and implement methods doPost() and doGet().

8 Example of an HTTP servlet import javax.servlet.*; import javax.servlet.http.*; public class GetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter output; // content type response.setContentType( "text/html" ); output = response.getWriter(); String name = request.getParameter( "customer" ); String addr = request.getParameter( "address" ); // create and send HTML page to client output.println( " " ); output.println( "A Simple Servlet Example" ); output.println( " " ); output.println( " Welcome to Servlets " ); output.println( "Dear " + name + " "); output.println( "How are you at " + addr + "? " ); output.println( " " ); output.close(); // close PrintWriter stream }

9 HttpServletRequest / HttpServletResponse Interfaces HttpServletRequest and HttpServletResponse extend interfaces ServletRequest and ServletResponse. The methods of HttpServlet receives two parameters: a HttpServletRequest object, which contains the request from the client, and a HttpServletResponse object, which contains the response to the client. When a client makes a HttpServlet call, the web server creates a HttpServletRequest and a HttpServletResponse object, and passes them to doGet() or doPost() methods.

10 HttpServletRequest Some important methods of HttpServletRequest : String getParameter (String name) returns the value of the named parameter Enumeration getParameterNames() returns names of all the parameters sent to servlet String[] getParameterValues( String name) returns an array of values of the named parameter Cookie[] getCookies() HttpSession getSession(Boolean create)

11 HttpServletResponse Some important methods of HttpServletResponse : void setContentType (String type) specifies the MIME type of the response to the browser, e.g., “text/html”. PrintWriter getWriter() obtains a character-based output stream. ServletOutputStream getOutputStream() obtains a byte-based output stream. void addCookie (Cookie cookie)

12 HTML file for doGet Servlet N.B. URL: Servlet HTTP GET Example Name Working Address Click the button to connect the servlet

13 DoGet import javax.servlet.*; import javax.servlet.http.*; public class GetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter output; // content type response.setContentType( "text/html" ); output = response.getWriter(); String name = request.getParameter( "customer" ); String addr = request.getParameter( "address" ); // create and send HTML page to client output.println( " " ); output.println( "A Simple Servlet Example" ); output.println( " " ); output.println( " Welcome to Servlets " ); output.println( "Dear " + name + " "); output.println( "How are you at " + addr + "? " ); output.println( " " ); output.close(); // close PrintWriter stream }

14 HTML file for doPost Servlet Servlet HTTP Post Example What is your favorite pet? Dog Cat Bird Snake None

15 DoPost public class PostServlet extends HttpServlet { private String animalNames[] ={ "dog", "cat", "bird", …}; public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { int animals[] = null, total = 0; //read in initial data of animals[] from a file // value = request.getParameter( "animal" ); // update survey data in animals[] for ( int i = 0; i < animalNames.length; ++i ) if ( value.equals( animalNames[ i ] ) ) ++animals[ i ]; // write animals[] to file & calculate % // send a message & survey results to client response.setContentType( "text/html" ); PrintWriter output = response.getWriter(); output.println( " " ); output.println( " Thank you! " ); output.println( "Thank you for participating." ); output.println( " Results: " ); // println results. output.println( " "); output.close(); } }

16 Servlet Database Connection A servlet can connect to a DB server using JDBC in the same way as CGI programs. A servlet can be started directly from browser, e.g., if this servlet implements doGet method. The servlet generates output in HTML format and passes them back to the browser for display. HTTP server Servlet DBMS system JDBC

17 A Servlet JDBC Paired with HTML public class Coffee extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = jdbc:mysql://jserv.cs.cityu.edu.hk: 3306/db_jdemo"; String query = "select COF_NAME, PRICE from COFFEES"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, "jdemo", "apple1"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); out.println(" "); ………….. HTML format… out.println(" "); out.println(" Name Price"); while (rs.next()) { String s = rs.getString("COF_NAME"); float f = rs.getFloat("PRICE"); String text = " " + s + " " + f; out.println(text); } stmt.close(); con.close(); out.println(" "); out.close(); } }

18 Applet and Servlet Servlet can be used with Applet as a replacement of CGI programs. Applet starts a servlet by POST (or GET), same way as starting a CGI program. Applet passes parameters to servlet in the same format as HTML form, e.g., “name=X+Jia&addr=CityU &ID= ”. Servlet can use getParameter to get parameter values. The Applet processes the results from the servlet in the same way as from a CGI program (suppose servlet sends results back in the same format as CGI). HTTP server must be in version 1.1 or above. It uses protocol: POST /jia/servlet/CoffeeServlet HTTP/1.1 Applet HTTP server Servlet DBMS system JDBC

19 An Applet connecting to a Servlet // java/js/WEB-INF/classes/CoffeeApplet.java // public class CoffeeApplet extends Applet implements Runnable { public synchronized void start() { if (worker == null) { Thread worker = new Thread(this); worker.start(); } } public void run() { Socket s; String sdata = “type=select_COFFEES”; DataInputStream in; PrintStream out; s = new Socket("jserv.cs.cityu.edu.hk",8080); in = new DataInputStream(s.getInputStream()); out = new PrintStream(s.getOutputStream()); out.println("POST /jia/servlet/CoffeeServlet HTTP/1.1"); out.println("Host: jserv.cs.cityu.edu.hk"); out.println("Content-type: application/x-www-form-urlencoded"); out.println("Content-length: " + sdata.length()); out.println(""); out.println(sdata); String line = in.readLine(); while (! line.equals("START_DATA")) line = in.readLine(); while (! line.equals("END")) { results.addElement(line); line = in.readLine(); } out.close(); in.close(); }

20 The Servlet Paired with Applet in JDBC The servlet working with an applet is similar to the CGI program in the 3-tier structure of JDBC. The servlet gets requests from applet via getParameter on “request” object. Note: the string posted from applet must have the parameter in the correct format! The servlet sends reply back to applet via println on “response” object. The servlet prepares reply to applet in a sequence of string lines, same as the CGI in 3-tier. Note: applet cannot process HTML statements easily. The applet working with the servlet is almost the same as the applet in the 3-tier structure of JDBC (except the format of request).

21 Servlet paired with the Applet public class CoffeeServlet extends HttpServlet { public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); a_req = request.getParameter("type"); if (a_req.equals("select_COFFEES")) { line = ReqSql(); out.println("START_DATA"); out.println(line); out.println(“END”); } static String ReqSql() { String url = "jdbc:mysql://jserv.cs.cityu.edu.hk: 3306/db_jdemo"; String query = "select COF_NAME, PRICE from COFFEES"; // make JDBC connection and executeQuery ………….. // process ResultSet to a line of string "results“ ………….. return(results.toString()); }

22 Servlet Cookies HTTP server is stateless, i.e., it does not keep any info about the clients. Some applications require the response to client requests depends on the info from the client earlier. Cookie is for this purpose. Cookies are extracted from the client’s data sent to the servlet. They are sent back to the client to store at the client side. A cookie is associated with an age. When the age expires, it will be removed. The cookies are included in the header of request and sent to the servlet together with request (new cookies are sent back browser via response. The servlet can analyse cookies and reponse to the requests accordingly. HTTPSession is a similar technology as the Cookie for the same purpose. Browser Servlet 1. generate cookies from client-requst 2. send cookies to browser for storage 3. include cookies in the next client-request

23 Methods on Cookies Cookies are strings, defined in javax.servlet.http.Cookie. Construct a Cookie: Cookie cookie = new Cookie( name, value); Set an age for a cookie: cookie.setMaxAge (seconds); Add a cookie to a response to the client: response.addCookie (cookie); Get cookies from a client’s request: Cookie cookies[]; cookies = request.getCookies(); Get cookie attributes: cookies[i].getname(); cookies[i].getValue(); Analyse cookies one by one: for (i = 0; i < cookies.length; i++) { cookies[i].getname() … cookies[i].getValue(); }

24 An example of using Cookies public class CookieServlet extends HttpServlet { private final static String names[] = { "C", "C++", "Java", "Visual Basic 6" }; private final static String isbn[] = { " ", " ", " ", " "}; public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String language = request.getParameter( "lang" ); Cookie c = new Cookie( language, getISBN( language ) ); c.setMaxAge( 120 ); // cookie expires // must precede getWriter response.addCookie( c ); response.setContentType( "text/html" ); PrintWriter output = response.getWriter(); utput.println( " " ); output.println( "Cookies" ); output.println( " " ); output.println( " Welcome to Cookies! " ); output.println( " "+lang+" is a great language." ); output.println( " " ); output.close(); // close stream }

25 An example of using Cookies (Cont.) public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{ Cookie cookies = request.getCookies(); response.setContentType( "text/html" ); PrintWriter output = response.getWriter(); output.println( " " ); output.println( "Cookies II" ); output.println( " " ); if ( cookies != null && cookies.length != 0 ) { output.println( " Recommendations " ); for ( int i = 0; i < cookies.length; i++ ) output.println(cookies[ i ].getName() + " Programming," + " ISBN#: " + cookies[ i ].getValue() + " " ); } else { output.println( " No Recommendations " ); output.println( "The cookies have expired." ); } output.println( " " ); output.close(); // close stream } private String getISBN( String lang ) { for ( int i = 0; i < names.length; ++i ) if (lang.equals(names[i])) return isbn[i]; }

26 HttpSession and Session Tracking When customers at an on-line store add items to their shopping carts, how does the server know what are already in the carts? When customers proceed to checkout, how can the server determine which previously created carts are theirs? HTTP is stateless. HttpSession is the solution to provide session tracking for clients. HttpSession is built on top of Cookies. It generates & maintains session IDs transparently.

27 Steps and APIs for Session Tracking Access the session embedded in Http request object: HttpSession session = request.getSession(true/false); Set attribute value in the session: session.setAttribute(“key”, value); Get attribute value of the session: xxxclass value = session.getAttribute(“xxxkey”); Get other information of the session: session.getId(); getCreationTime(), getLastAccessedTime(), …. Boolean session.isNew(); Remove session data: removeAttribute("key");

28 Rewrite the Example of Cookies by Sessions public class SessionTracking extends HttpServlet { public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String lang = request.getParameter( "lang" ); HttpSession session = request.getSession( true ); //setAttribute passes session to browser via output session.setAttribute( lang, getISBN( lang)); … output.println(…+ session.isNew()?...); output.println(…+ session.getID()...); output.println(…+ session.getCreationTime()...); output.println(…+ session.getLastAccessedTime()); …….. public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { HttpSession session = request.getSession( false ); if ( session != null ) valueNames = session.getAttributeNames(); else valueNames = null; if ( valueNames != null) { output.println( " List of your purchase " ); ……. while ( valueNames.hasMoreElements() ) { name = valueNames.nextElement().toString(); value = session.getAttribute( name ).toString(); output.println( name + …+ value + " " ); } else output.println( “No purchase" ); }

29 Comparisons of Cookies and Sessions Cookies is persistent beyond closedown of browser (info is stored on disk); while Session is only valid for one browsing-session (stored in browser’s memory). Cookies have limited size (around 300 cookies for a server, 20 cookies per client and 4K bytes of data per cookie); while session data has no limit of size. Due to security reason, some browsers don’t support cookies (or they can be turned off).