Presentation is loading. Please wait.

Presentation is loading. Please wait.

INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

Similar presentations


Presentation on theme: "INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES"— Presentation transcript:

1 INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES
Chapter 6: HTTP protocol Servlets and CGI Rufin Soh

2 Content HTTP HTML HTML forms HTTP protocol Forms SUBMIT HTTP exchanges
Forms SUBMIT : GET method Forms SUBMIT : POST method HTTP challenges Client-side scripting Server-side scripting Java Servlets What are servlets What is a Servlet used for? Servlet working mode ? The Java API for servlets Servlet example Install your servlet Run your servlet from the browser Java servlet vs CGI HTTP HTTP protocol HTTP exchanges HTTP requests and responses HTTP headers HTTP requests format HTTP session examples HTTP responses HTTP responses status codes HTML HTML language HTML concepts HTML examples HTML editors A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

3 Content HTTP HTTP protocol HTTP exchanges HTTP requests and responses
HTTP headers HTTP requests format HTTP session examples HTTP responses HTTP responses status codes A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

4 HTTP protocol HTTP (Hyper Text Transfer Protocol) is a protocol used on the web for hypermedia systems It enables data transfer and negociation of the transfered data types. A web server is a program that receives HTTP request from different clients (www users) and return requested documents. World-Wide Web (WWW) is a network made of a set of servers ( that speak HTTP) and the information that they contains. Actual HTTP version is 1.1 A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

5 HTTP exchanges An HTTP request has the following steps:
The client makes a TCP connexion on HTTPD port 80. The client transmit a request ( a line os text that ends with a CR LF) The request format is <Méthode> URL The server returns the document specified in the URL The server ends the connexion Some servers support a keep-alive features that help to keep the connexion for many transfers for the same document. The HTTP server is stateless: It does not keep any information on the clients A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

6 HTTP requests and responses
HTTP/1.0 enables the transfer of documents in many formats, following the MIME standard(Multi-purpose Internet Mail Extensions). An HTTP message may be a client request or a server response. The request-response format is A request-response line many headers an empty line the request-response body A request-response line Headers Empty line Body A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

7 HTTP headers HTTP-Version: Identifies the HTTP version. The clients are going to indicate here which protocol they are using. The default value is HTTP/0.9 Date: Date when the message has been created Forwarded: Identifies the sender machine. Useful when intermediaries proxies are used Mime-Version: The MIME version of the client Accept: The client will mention the type of documents that he can accept Accept-Charset: The client specified the supported character encoding. The default values are US-ASCII and ISO If-Modified-Since: Specified a date. Useful for the browser to request a document from the server only if this one has been modified since the date indicated on the local cached copy. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

8 HTTP headers (2) User-Agent: Identification of WWW clients
Retry-After: Used by an HTTP server to mention thsat it temporally not availaible Server: The server identification. Content-Length: The length in bytes of the body in HTTP message (request or response) Content-Type: The HTTP message (request or response) body’s MIME encoding type e.g. text/plain, text/html, text/xml, … Expires: Timestamp for a document. Used to manage documents caches. Last-Modified: Date of the latest modification of the document. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

9 HTTP requests format HTTP requests are formatted: <Method> URL
<Method> URL HTTP/1.0 Requests may contains parameters in their URL GET URL?parameter1+parameter2+…+parameterN Some of these programs may required options. They are also transmitted in the URL: GET /cgi-bin/search?mozart HTTP/1.0 A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

10 HTTP session examples GET method: Ask the server to read a web page. This may be <a HREF="http://www.info.uqam.ca/Test/text.html"> Anchor </a> Connects to the server « www.info.uqam.ca » on the port « 80 » GET Test/texte.html HTTP/1.0 Accept: text/plain , image/* If-Modified-Since: Wed, 10 Sep :20:21 GMT Referer: User-Agent: Mozilla/2.0 empty line HTTP server Request HTTP/ OK Date: Wed, 10 Sep :20:21 GMT Server: NCSA/1.5.2 Mime-Vesion: 1.0 Content-Type: text/html Last-Modified: Wed, 10 Sep :20:23 GMT Content-Length: 139 empty line <html> ……</html> HTTP server Response A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

11 HTTP session examples (3)
HEAD method: Ask the server to read the web page header. E.g. a search engine request HTTP server HEAD Test/texte.html HTTP/1.0 User-Agent: Mozilla/2.0 Referer: Empty line HTTP/ OK Date: Wed, 10 Sep :20:21 GMT Server: NCSA/1.5.2 Mime-Vesion: 1.0 Content-Type: text/html Last-Modified: Wed, 10 Sep :20:23 GMT HTTP server A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

12 HTTP session examples (4)
GET method with: GET cgi/research?item1+item2+item3 HTTP/1.0 Accept: */* Accept-language: en, fc User-Agent: Mozilla/2.0 Host: saturne.info.uqam.ca Ligne blanche GET method from a form with: GET /cgi/saisie?champ1=Val1&champ2=Val2 Accept: */* Accept-language: en, fc User-Agent: Mozilla/2.0 Host: saturne.info.uqam.ca Ligne blanche A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

13 HTTP session examples (5)
POST method from a form with: champ1=Val1 and champ2=Val2 POST /cgi/saisie Accept: */* Accept-Language: en, fc User-Agent: Mozilla/2.0 Host: saturne.info.uqam.ca Content-type: multipart/form-data; boundary= Content-Length: 112 empty line Content-Disposition: form-data; name="Champ1" Val1 Content-Disposition: form-data; name="Champ2" Val2 A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

14 HTTP responses Every HTTP response is identfied with a code:
Response Class Meaning Example 1XX Informational unused 2xx Success 200 OK 3xx Redirection to another server 301 MOVED TEMPORARILY 4xx Client did something wrong 401 UNAUTHORISED 5xx Server did something wrong 500 INTERNAL SERVER ERROR A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

15 HTTP responses status codes
2xx OK The request was fulfilled. CREATED 201 success following a POST command. Accepted 202 The request has been accepted for processing, but the processing has not been completed. Partial Information 203 The returned meta information is not a definitive . No Response 204 Server has received the request but there is no information to send back, and the client should stay in the same document view. 3xx Moved 301 The data requested has been assigned a new URI, the change is permanent. Found 302 The data requested actually resides under a different URL. Method 303 Like the found response, this suggests that the client go try another network address. In this case, a different method may be used too, rather than GET. Not Modified 304 A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

16 HTTP responses status codes (2)
4xx Bad request 400 The request had bad syntax or was inherently impossible to be satisfied. Unauthorized 401 The client should retry the request with a suitable Authorization header. PaymentRequired 402 The client may retry the request with a suitable ChargeTo header. Forbidden 403 The request is for something forbidden. Authorization will not help. Not found 404 The server has not found anything matching the URI given 5xx Internal Error 500 The server encountered an unexpected condition which prevented it from fulfilling the request. Not implemented 501 The server does not support the facility required. Service temporarily overloaded 502 The server cannot process the request due to a high load. Gateway timeout 503 This is equivalent to Internal Error 500, but in the case of a server which is in turn accessing some other service, this indicates that the respose from the other service did not return within a time that the gateway was prepared to wait. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

17 Content HTTP HTML HTML language HTML concepts HTML examples
HTML editors A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

18 HTML language HyperText Markup Language is:
A marking language used to specified: Pages tables and frames, … format Fonts, colors, … attributes A language used to describe hypermedia documents: Images text hypertext links between documents hosted on different sites A normal text language. This enables its portability between different machines. A tagged language. Tag effects are applied to the content between the opening tag and the closing one A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

19 HTML concepts HTML is a markup language: a language that just consist of adding tags to simple ASCII text without any formatting. Most of the tags are “twins”. <html> </html> Tells you the beginning of an HTML document <head> </head> Tells you the section of informations that is not going to be displayed <title> </title> Indicates the title of the document (not to be displayed) <body> </body> Indicates the section of informations that are going to bre displayed In general, a tag has a name (mandatory), with optional sets of attributes whith an associated value for some of them. E.g. <TagName Attribute_1_Name="Attribute_1_Value" Attribute_2_Name="Attribute_2_Value" Attribute_1_Name > A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

20 HTML examples A Minimal HTML example is <html>
<head> <TITLE>A minimal example</TITLE> </head> <body> This the text of my document </body> </html> A more complete HTML example is <HTML> <HEAD> <TITLE>How to call a servlet?</TITLE> </HEAD> <BODY BGCOLOR="white" TEXT="black" LINK="blue" VLINK="purple" ALINK="yellow"> <H1>How to call a servlet?</H1> <H2>Form</H2> <P>This form uses the P<SMALL>OST</SMALL> method: <BR><FORM ACTION="http://localhost:8080/servlet/query" METHOD="POST"> <INPUT NAME="query"> <INPUT TYPE="SUBMIT" VALUE="Post"> </FORM> <H2>Hyperlink</H2> <P>This hyperlink uses the G<SMALL>ET</SMALL> method: <BR><A HREF="http://localhost:8080/servlet/query?java">http://localhost:8080/servlet/query?java</A> </BODY> </HTML> A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

21 HTML editors An HTML editor is a tool that you may use to build web pages, by generating HTML code from an edited text: FrontPage Netscape Composer PageMill HotMetal Pro Amaya Macromedia DreamWeaver 3 or 4 Hypertext Builder 7 Very simple Most recommended A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

22 Content HTTP HTML HTML forms Forms SUBMIT Forms SUBMIT : GET method
Forms SUBMIT : POST method A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

23 HTML forms An HTML form is a set of elements used to ritrieve informations from the user. Once filled, the form can be submitted to a processing program, that runs on the server. The <FORM> tag may have an attribute “METHOD” that can take the values GET or POST. The difference between the two resides in how the form data are going to be sent to the server indicated in the “ACTION” attribute. DESCRIPTION: <FORM NAME = “name” ACTION="URL" METHOD="Action"> ACTION : Provides the URL address where the request with the form content will be sent. If the field ACTION is absent, the request will be sent to the current server. METHOD : HTTP command used to communicate with the HTTP server. There are two methods, GET and POST. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

24 HTML forms Nearly all tha form elements contain a NAME = “xxx” and VALUE = “yyy” attributes that are used to send the form content to the server mentionned in the ACTION = “servletURL” attribute. Every form MUST contain a SUBMIT element. If many SUBMIT buttons are used in the same form, you can distinguish them with the NAME = “xxx” attribute which will be sent in the request to the server.. An HTTP may call programs via CGI or servlets interfaces: Netscape Form HTML http server Program or Script (3) CGI Data (1) (2) servlet (4) (5) A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

25 Forms examples (2) <FORM METHOD="POST" ACTION="http://www.labunix.uqam.ca/cgi-bin/post.cgi"> Nom <INPUT NAME="Nom"><P> Prénom <INPUT NAME="Prenom"> <OL> <LI> <INPUT TYPE="checkbox" CHECKED NAME="etat"   VALUE="Marie">Marié <LI> <INPUT TYPE="checkbox" NAME= " langue" VALUE="francais"> Canadien </OL> Volontaire <UL> <LI> <INPUT TYPE="radio" NAME= " info" VALUE="Oui" CHECKED> oui <li> <INPUT TYPE="radio" NAME= "info" VALUE="Non"> Non <LI> <INPUT TYPE="radio" NAME= "info" VALUE="Ne sait pas"> Ne sait pas </UL> <INPUT TYPE="submit" VALUE="Ok"> <INPUT TYPE="reset" VALUE="Annuler"> </FORM> A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

26 Forms SUBMIT During the transmission of the form content to the server mentionned in the ACTION attribute, the browser encodes this content: All the spaces are replaced by ‘+’ signs Non alpha-numeric characters are replaced by a %xx sequence, where xx corresponds to the hexadecimal representation of the character ASCII code, Carriage return are encoded with %0a for textarea.. An HTML document may content many forms. This may help to optimize the use of many SUBMIT buttons: any form content is transmitted with its SUBMIT button. The ACTION attribute generally contains the servlet or CGI program URL or an address A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

27 Forms SUBMIT : GET method
With the GET method, browser sends the form’s information after the CGI (or servlet) URL mentionned in the ACTION attribute, with a “?” between them. E.g. You can see these values in the brower URL textfield, when the server sends back the response. Adv: It may be used to save a bookmark of the response so you may reactivate the script later with the same data without fillig the form. You can include the link in a document DisAdv : All the form informations are visible and this may give a very big URL. The servlet or CGI program will retrive the rigth part of “?” in the environment variables. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

28 Forms SUBMIT : POST method
With the POST method, data are sent to the server (the CGI script or your servlet) in a separate way, in the body of the HTTP request. Advantages: suitable when you have many data to transmit, informations transmitted are not visible. Disadvantages: You can’t save a bookmark on the response, if the servlet or the script application is moved the request can not be redirected. The difference between GET and POST is very important mainly for the programmer of the servlet or script which is supposed to receive the form data. When using an existing servlet or script, you need to know which method is used to send data. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

29 Content HTTP HTML HTML forms HTTP challenges Client-side scripting
Server-side scripting A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

30 Client-side scripting
Java applets are a great solution to create highly interactive Web sites. Not dynamic web pages. There are other solutions such as JavaScript, Shockwave, ActiveX or the old reliable forms: those are client side solution . Admittedly forms are less fashionable than say applets but many popular sites make extensive use of them. For example, search engines like Infoseek or online shops like Amazon.com rely extensively on forms. Forms are implemented through a combination of HTML and server-side scripting. In this section, we will see how to write server-side scripts with Java servlet A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

31 Server-side scripting
A Web server simply fetches files upon request from browsers. For example, when a browser requests "index.html", the server sends the corresponding file over the network. For more complex requests like forms, the server calls specific programs. These programs are known as scripts because, historically, most of them were written with scripting languages like Perl. The scripts collect data from the forms and dynamically build Web pages in response. These pages do not exist on the server hard-disk, they are built dynamically in response to browser requests -- hence the name dynamic Web pages. Server-side scripting is still very popular for several reasons: it is totally independent of the browser since everything takes place on the server; complex requests may execute faster on the server; it can be made safer since the programs run under direct control of the server administrator. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

32 Server-side scripting
The original standard for server-side scripts is CGI or Common Gateway Interface. CGI: Advantages simple and widely supported. Disadvantages: it is not very efficient because the server launches one copy of the script per request, the overhead can be significant for popular sites. Vendors have developed proprietary alternatives such ISAPI (Microsoft) and NSAPI (Netscape) to address the performance issue. JavaSoft recently proposed the Java servlets as a standard efficient alternative to CGI. The servlet API is a Java extension. Java extensions are optional standard packages. Being standard packages, they are endorsed by JavaSoft and widely supported in the industry. Being optional, they are not available on every platform unlike the Core API (java.io, java.awt, etc.). Indeed it does not make sense to support servlets anywhere but on servers. To differentiate Java extensions from the Core API, the package names start with javax (mind the x). A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

33 Content HTTP HTML HTML forms HTTP challenges Java Servlets
What are servlets What is a Servlet used for? Servlet working mode ? The Java API for servlets Servlet example Install your servlet Run your servlet from the browser Java servlet vs CGI A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

34 What are servlets Servlets are for server, what Applets are for browser They are “normal” java programs that uses the Java servlet API which contains the packages: Javax.servlet.* Javax.servlet.http.* They are Included in the archives jsdk.jar (Java Servlet Development Kit). Servlets are interpreted in a JVM (Java Virtual Machine) running in a compatible web server (e.g. tomcat) A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

35 What is a Servlet used for ?
The same as CGI, servlets are used to extend web server functionalities, processing some operations demanded in HTTP requests and including the results in the responses. Actually, servlets are widely used with HTTP for dynamically publishing HTML web pages. But Servlets are not specific to Web servers. The API is flexible and supports most Internet servers, e.g. mail server (with SMTP, POP), FTP server … Of course JavaSoft recognized that most programmers would write servlets for HTTP servers, i.e. Web servers, and it has standardized an HTTP-specific version of servlets, HttpServlet. In this section, we will concentrate on HTTP-specific servlets. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

36 Servlet working mode ? The client fills an HTML form SUBMIT it: sends it to the server The server receives it and redirect it to the servlet using the ACTION tag <FORM NAME=”MyForm” ACTION=”http://www.WebServer.com/servlet/Search” METHOD=”POST”> Since the servlet is a java program, it behaves exactly like any program with an access to all the java functionalities. So it can communicate with external resources such as files (read and write), databases and other applications (even remotely via RMI, CORBA, …) and after the processing it may use resulting data to dynamically build a web page to send back. The servlet sends back the HTML page to the user. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

37 The Java API for servlets
Javax.servlet.* Javax.servlet.http.* Included in the archives jsdk.jar (Java Servlet Development Kit). A servlet is Java class that implements the javax.servlet.Servlet interface. This interface defines only five methods: service() is the heart of servlets. The server calls service() to execute requests. service() accepts a ServletRequest and a ServletResponse objects as parameters. ServletRequest encapsulates the client request while ServletResponse exposes methods to return information to the client; init() is the place to initialize the servlet. init() accepts a ServletConfig object as parameter. ServletConfig maintains the server configuration; getServletConfig() must return the ServletConfig object passed to init(); destroy() cleans up the servlet; getServletInfo() returns a string with copyright information. The “Java Servlet” API provides a number of methods that a servlet may (instead MUST) implement: A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

38 The Java API for servlets (2)
Init(): Yhis method will run oonce when the servlet program is loaded by the server. This method may be personalized (by rewritting the default code), e.g when you want to initialize a database connexion with JDBC, …. Destroy(): Also executed once, when the server stops and drops the servlet. Generally the default method is enough but you may also use it to disconnect to your database, by rewritting the method. Services doGet(), doPost(): Those methods are called by the service() method. They differe from the previous methods in that they are called for any client request. The appropriate doXXX() method must be invoked according to the HTTP method asked in the request through the METHOD=”GET” or METHOD=”POST” attribute. Those methods are where all the processing code are going to be included. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

39 Servlet life cycle The servlet is automatically loaded when the web server starts, or after the first client request. The server creates one instance of the servlet. The server calls the servlet’s init() method. If a client request reaches the servlet (the server remember it if this request has been the originator of the servlet loading) The server creates a Request Object specific to this request. The server creates a Response Object specific to this request. The server calls the servlet’s service() method to transmit the Request and Response Objects. The service() method receives informations on the request to process from Request and Response Objects, and sends back response to the client after processing using Request and Response objects’ methods. The service() methods may call doGet() or doPost() or even new methods from your own.. For new cleint request, resume from line 4. Once the servlet is no more in use, the web server invokes the destroy() method. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

40 Servlet example HttpServlet. HttpServlet is the class that implements the Servlet interface but provides additional methods specific to Web servers. One typically use of HttpServlet is with HTML forms. To illustrate HttpServlet, we will see a simple servlet, Query, that lookups a word in a dictionary and returns its definition in a dynamic Web page. Servlets execute three steps to process a request: analyze the request, e.g. for a form, collects the value of the various fields; execute the request, e.g. query a database; create a response, e.g. format the result of the query in a Web page. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

41 Servlet example (your web page and form)
POST As explained previously, POST is only available with forms. HTMLcode for a simple POST form: The <FORM> tag takes two parameters: ACTION is the URL of the servlet; METHOD forces the method to POST (it defaults to GET). The first <INPUT> tag is a text field, the second one is a button. <HTML> <HEAD> <TITLE>How to call a servlet?</TITLE> </HEAD> <BODY BGCOLOR="white" TEXT="black" LINK="blue" VLINK="purple" ALINK="yellow"> <H1>How to call a servlet?</H1> <H2>Form</H2> <P>This form uses the P<SMALL>OST</SMALL> method: <BR><FORM ACTION="http://localhost:8080/servlet/query" METHOD="POST"> <INPUT NAME="query"> <INPUT TYPE="SUBMIT" VALUE="Post"> </FORM> <H2>Hyperlink</H2> <P>This hyperlink uses the G<SMALL>ET</SMALL> method: <BR><A HREF="http://localhost:8080/servlet/query?java">INE 4481 example for GET</A> </BODY> </HTML> A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

42 Servlet example (submit form - doPost())
In the servlet, the form data is routed to the doPost() method. My Query servlet implements doPost() as : As you can see, the servlet retrieves the form fields through the HttpServletRequest::getParameter() method. It uses the name of the <INPUT> tag to identify the parameters. Servlet code follows protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String query = req.getParameter("query"); String definition = getDefinition(query); doResponse(query,definition,resp); } A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

43 Servlet example (submit form - doGet())
The GET method also works with forms but I find it more useful with hyperlinks. This is an example of a hyperlink that jumps to a dynamic page: <A HREF="http://localhost:8080/servlet/query?java">INE 4481 example for GET </A> the beginning of the the URL (before ?) points to the servlet. The parameter appears after the question mark. In the servlet, the request is routed to doGet(): Servlet code follows protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String query = req.getQueryString(); String definition = getDefinition(query); doResponse(query,definition,resp); } A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

44 Servlet example (submit form - doGet())
Again the servlet retrieves the parameters from the HttpServletRequest object. In this example, it uses HttpServletRequest::getQueryString(). getQueryString() works fine if there is just one parameter. To work with more parameters, it is necessary to use named parameters like POST does. An URL with named parameters is of the form: Parameter names and values are grouped in pairs separated by ampersand &. This URL has two parameters: detail and frame and their values are full and no respectively. A servlet retrieves named parameters through HttpServletRequest::getParameter() as always. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

45 Servlet example (execute the request)
After analyzing the request, the servlet must prepare a response. Typically the servlet connects to a database or reads files on the server. Another popular option is to create an but you are only limited by your imagination. Processing the request may involve low-level access to the hardware. Here, my Query servlet checks the word against its dictionary: protected String getDefinition(String word) { String definition = dictionary.getProperty(word.toLowerCase()); if(null == definition) return "I have never heard of it."; else return definition; } A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

46 Servlet example (Create a response)
protected void doResponse(String query, String answer,HttpServletResponse resp) throws IOException { // first prepare the response as a Web page // StringBuffer is convenient to know the length of the page StringBuffer buffer = new StringBuffer(); buffer.append("<HTML>\n"); buffer.append("<HEAD>\n"); buffer.append("<TITLE>Query</TITLE>\n"); buffer.append("</HEAD>\n"); buffer.append("<BODY BGCOLOR=\"white\" TEXT=\"black\" LINK=\"blue\" VLINK=\"purple\" ALINK=\"yellow\">\n"); buffer.append("<H1>Query</H1>\n"); buffer.append("<P>Query has this to say about <EM>"); buffer.append(word); buffer.append("</EM>:\n<P><BLOCKQUOTE>"); buffer.append(definition); buffer.append("</BLOCKQUOTE>\n"); buffer.append("<HR WIDTH=\"20%\" ALIGN=\"LEFT\">\n"); buffer.append("<P>Query by <A HREF=\"http://www.geocities.com/srufin\"><I>INE 4481</I> sprl</A>.\n"); buffer.append("<BR>Visit <A HREF=\"http://www.javacats.com/\">Digital Cat</A> for Java resources.\n"); buffer.append("</BODY>\n"); buffer.append("</HTML>"); // next pass the response to the client resp.setContentType("text/html"); resp.setContentLength(buffer.length()); resp.getOutputStream().print(buffer.toString()); } A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

47 Servlet example (Create a response)
After executing the request, the servlet must return a response to the client. To communicate with the client, the servlet uses the HttpServletResponse object, a specialized version of ServletResponse. Two cases are possible: either an error occurred or some result is available. If an error occurred, the servlet can either throw an exception or return an error through HttpServletResponse::sendError(). If there is no error, the servlet will dynamically create a Web page. To return a Web page, the servlet must first specify the MIME content-type of the response with ServletResponse::setContentLength(). Web pages are of type text/html but servlets can return data in any format notably including GIF (image/gif) or JPEG (image/jpeg) images. Additionally, a servlet may set a content-length with ServletResponse::setContentLength(). Setting length is optional and should be done only if it is not too costly. Setting a wrong length is dangerous as the server may raise an exception. Finally the servlet writes its response in the stream returned by ServletResponse::getOutputStream(). My Query servlet constructs a Web page in memory (which is convenient to compute the length), set the content-type and length and send the page to the Web browser. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

48 Servlet example (overview)
/** * Query is a simple querying mechanism that illustrates how to write * HTTP servlets. * 20 sept 2001 */ import javax.servlet.http.*; import javax.servlet.*; import java.io.*; import java.util.*; public class Query extends HttpServlet { private Properties dictionary = new Properties(); public void init(ServletConfig config) throws ServletException { } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { } protected String getDefinition(String word) protected void doResponse(String word, String definition,HttpServletResponse resp)throws IOException { } public String getServletInto() } JAVA servlet API Servlet creation A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

49 Install the servlet Once the sevlet is implemented, you will need to install it on an adequate server. e.g. Apache seb server + the ApacheJServ module Oracle Application server + Jservlet Cartridge Apache tomcat webserver Etc… On this server, you also need a Java Running Environment (JRE 1.1.X, 1.2) and the JSDK 2.0 or 2.1. The actual installation may be different from one srever to another. But as for CGI_BIN, your servlets are generally installed and declared in a personal “sandbox”. It is actually a space that may be submitted to many access restrictions (files, network, …) depending on the server administrator configuration. A servlet without restrictions could stop a web hosting server with a simple “system.exit()” ! command. On the client side there is nothing to install, you just need your browser and the web server URL. You may use the “ServletRunner” provided with the JSDK when implementing your servlet, to simulate a web server (cf JBUILDER 4) Important: follow up the webserver user guide to identify the proper sandbox and check if there is no futher configuration to do. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

50 Run your servlet from the browser
There are many ways of running your servlet: You may call directly by typing the complete servlet URL in your browser You may indicate the servlet in the form tag (inside <FORM> …. </FORM>), with ACTION attribute, using the GET and POST methods to send the form content (entered by the user) to the servlet. You may indicate the servlet in the <SERVLET> tag of an HTML document (like for applet) You may use a link like in our example A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES

51 Java servlet vs CGI Servlets have four distinct advantages over CGI and other APIs: familiarity: servlets are written in Java, the programming language you've come to know and love. Servlets have access to all the Java packages and the JavaBeans on the market; portability: servlets are portable across servers, delivering the Java promise of write once, run anywhere. Netscape, Apache and IIS, arguably the three most popular Web servers, are supported by Javasoft. Most other vendors have announced plans to support the servlet API in their products; safety: servlets are written in Java and they benefit from the safety features inherent to Java, like memory management; performance: servlets are more efficient than CGI. A.Obaid-Wilfried Probst – Rufin Soh INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES


Download ppt "INE4481 DISTRIBUTED DATABASES & CLIENT-SERVER ARCHITECTURES"

Similar presentations


Ads by Google