10-Jun-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Java Servlet & JSP © copyright 2005 SNU OOPSLA Lab.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
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
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
13-Jul-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
Server Side Programming Web Information Systems 2012.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
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.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
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.
Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send .
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
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. Servlets When we run small Java programs within a browser these are referred to as Applets... And when we run small Java programs within.
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
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.
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.
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.
Introduction to Servlets Allen Day. Notes This is a training NOT a presentation Please ask questions Prerequisites.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Servlets and Java Server Pages
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Chapter 4 Request and Response. Servlets are controlled by the container.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
CS122B: Projects in Databases and Web Applications Spring 2017
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Servlet Fudamentals.
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
Servlets.
CS122B: Projects in Databases and Web Applications Spring 2018
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Servlets 7-Apr-19.
CS122B: Projects in Databases and Web Applications Winter 2019
Presentation transcript:

10-Jun-15 Servlets

2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download a file, send A server is also the software that responds to these requests; a client could be the browser or other software making these requests Typically, your little computer is the client, and someone else’s big computer is the server However, any computer can be a server It is not unusual to have server software and client software running on the same computer

3 Apache Apache is a very popular server 66% of the web sites on the Internet use Apache Apache is: Full-featured and extensible Efficient Robust Secure (at least, more secure than other servers) Up to date with current standards Open source Free Why use anything else?

4 Ports A port is a connection between a server and a client Ports are identified by positive integers A port is a software notion, not a hardware notion, so there may be very many of them A service is associated with a specific port Typical port numbers: 21 —FTP, File Transfer Protocol 22 —SSH, Secure Shell 25 —SMTP, Simple Mail Transfer Protocol 53 —DNS, Domain Name Service 80 —HTTP, Hypertext Transfer Protocol 8080 —HTTP (used for testing HTTP) 7648, 7649 —CU-SeeMe —Quake III These are the ports of most interest to us

5 Ports II My UPenn Web page is: But it is also: The http: at the beginning signifies a particular protocol (communication language), the Hypertext Transfer Protocol The :80 specifies a port By default, the Web server listens to port 80 The Web server could listen to any port it chose This could lead to problems if the port was in use by some other server For testing servlets, we typically have the server listen to port 8080 In the second URL above, I explicitly sent my request to port 80 If I had sent it to some other port, say, 99, my request would either go unheard, or would (probably) not be understood

6 CGI Scripts CGI stands for “Common Gateway Interface” Client sends a request to server Server starts a CGI script Script computes a result for server and quits Another client sends a request client server client script Server starts the CGI script again Etc. script Server returns response to client script

7 Servlets A servlet is like an applet, but on the server side Client sends a request to server Server starts a servlet Servlet computes a result for server and does not quit Another client sends a request client server client servlet Server calls the servlet again Etc. Server returns response to client

8 Servlets vs. CGI scripts Advantages: Running a servlet doesn’t require creating a separate process each time A servlet stays in memory, so it doesn’t have to be reloaded each time There is only one instance handling multiple requests, not a separate instance for every request Untrusted servlets can be run in a “sandbox” Disadvantage: Less choice of languages (CGI scripts can be in any language)

9 Tomcat Tomcat is the Servlet Engine than handles servlet requests for Apache Tomcat is a “helper application” for Apache It’s best to think of Tomcat as a “servlet container” Apache can handle many types of web services Apache can be installed without Tomcat Tomcat can be installed without Apache It’s easier to install Tomcat standalone than as part of Apache By itself, Tomcat can handle web pages, servlets, and JSP Apache and Tomcat are open source (and therefore free)

10 Servlets A servlet is any class that implements the javax.servlet.Servlet interface In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead Servlets, like applets, usually lack a main method, but must implement or override certain other methods

11 What does a servlet do? 1. Read any data sent by the user 2. Look up any information about the request that is embedded in the HTTP request 3. Generate the results 4. Format the results inside a document 5. Set the appropriate HTTP parameters 6. Send the document back to the client From: Core Servlets and JavaServerPages, by Marty Hall

12 Important servlet methods, I When a servlet is first started up, its init(ServletConfig config ) method is called init should perform any necessary initializations init is called only once, and does not need to be thread-safe Every servlet request results in a call to service(ServletRequest request, ServletResponse response ) service calls another method depending on the type of service requested Usually you would override the called methods of interest, not service itself service handles multiple simultaneous requests, so it and the methods it calls must be thread safe When the servlet is shut down, destroy() is called destroy is called only once, but must be thread safe (because other threads may still be running)

13 HTTP requests When a request is submitted from a Web page, it is almost always a GET or a POST request The HTTP tag has an attribute action, whose value can be "get" or "post" The "get" action results in the form information being put after a ? in the URL Example: 8&q=servlets The & separates the various parameters Only a limited amount of information can be sent this way "put" can send large amounts of information

14 Important servlet methods, II The service method dispatches the following kinds of requests: DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method These are the two methods you will usually override doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it public void doGet(HttpServletRequest request, HttpServletResponse response) { doPost(request, response); }

15 A “Hello World” servlet (from the Tomcat installation documentation) public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + " \n" + " Hello \n" + " \n" + " Hello World \n" + " "); } Don’t worry, we’ll take this a little at a time!

16 The superclass public class HelloServlet extends HttpServlet { Every class must extend GenericServlet or a subclass of GenericServlet GenericServlet is “protocol independent,” so you could write a servlet to process any protocol In practice, you almost always want to respond to an HTTP request, so you extend HttpServlet A subclass of HttpServlet must override at least one method, usually one doGet, doPost, doPut, doDelete, init and destroy, or getServletInfo

17 The doGet method public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { This method services a GET request The method uses request to get the information that was sent to it The method does not return a value; instead, it uses response to get an I/O stream, and outputs its response Since the method does I/O, it can throw an IOException Any other type of exception should be encapsulated as a ServletException The doPost method works exactly the same way

18 Parameters to doGet Input is from the HttpServletRequest parameter Our first example doesn’t get any input, so we’ll discuss this a bit later Output is via the HttpServletResponse object, which we have named response I/O in Java is very flexible but also quite complex, so this object acts as an “assistant”

19 Using the HttpServletResponse The second parameter to doGet (or doPost ) is HttpServletResponse response Everything sent via the Web has a “MIME type” The first thing we must do with response is set the MIME type of our reply: response.setContentType("text/html"); This tells the client to interpret the page as HTML Because we will be outputting character data, we need a PrintWriter, handily provided for us by the getWriter method of response : PrintWriter out = response.getWriter(); Now we’re ready to create the actual page to be returned

20 Using the PrintWriter From here on, it’s just a matter of using our PrintWriter, named out, to produce the Web page First we create a header string: String docType = " \n"; This line is technically required by the HTML spec Browsers mostly don’t care, but HTML validators do care Then use the println method of out one or more times out.println(docType + " \n" + "... "); And we’re done!

21 Input to a servlet A GET request supplies parameters in the form URL ? name = value & name = value & name = value (Illegal spaces added to make it more legible) Actual spaces in the parameter values are encoded by + signs Other special characters are encoded in hex; for example, an ampersand is represented by %26 Parameter names can occur more than once, with different values A POST request supplies parameters in the same syntax, only it is in the “body” section of the request and is therefore harder for the user to see

22 Getting the parameters Input parameters are retrieved via messages to the HttpServletRequest object request Most of the interesting methods are inherited from the superinterface ServletRequest public Enumeration getParameterNames() Returns an Enumeration of the parameter names If no parameters, returns an empty Enumeration public String getParameter(String name) Returns the value of the parameter name as a String If the parameter doesn’t exist, returns null If name has multiple values, only the first is returned public String[] getParameterValues(name) Returns an array of values of the parameter name If the parameter doesn’t exist, returns null

23 Enumeration review An Enumeration is almost the same as Iterator It’s an older class, and the names are longer Example use: Enumeration e = myVector.elements(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); }

24 Example of input parameters public void doGet(HttpServletRequest request, HttpServletResponse response) {... stuff omitted... out.println(" Hello"); String names[] = request.getParameterValues("name"); if (names != null) for (int i = 0; i < names.length; i++) out.println(" " + names[i]); out.println("!"); }

25 Java review: Data from Strings All parameter values are retrieved as String s Frequently these Strings represent numbers, and you want the numeric value int n = new Integer( param ).intValue(); double d = new Double( param ).doubleValue(); byte b = new Byte( param ).byteValue(); Similarly for short, float, and long These can all throw a NumberFormatException, which is a subclass of RuntimeException boolean p = new Boolean( param ).booleanValue(); But: char c = param.charAt(0);

26 What’s left? We’ve covered enough so far to write simple servlets, but not enough to write useful servlets We still need to be able to: Use configuration information Authenticate users Keep track of users during a session Retain information across different sessions Make sure our servlets are thread safe Communicate between servlets But remember: The most difficult program in any language is Hello World!

27 The End