Servlets Serverside java programming Material in this ppt

  • Slides: 55
Download presentation
Servlets Server-side java programming Material in this ppt is partly gleaned from chapters 1

Servlets Server-side java programming Material in this ppt is partly gleaned from chapters 1 and 2 of Jason Hunter’s text, but also includes Tomcat installation information.

remarks • Javax. servlet and javax. servlet. http packages were the first java classes

remarks • Javax. servlet and javax. servlet. http packages were the first java classes to be released as open source and now reside at Apache Software Foundation. • Open-source developers like Hunter handle bug fixes. • Tomcat is the official servlet container specification and is open-sourced. • Hunter’s book covers Servlet 2. 2 API • Text examples may still be available at http: //www. oreilly. com/catalog/jservlet 2

What are the (server-side) options? • • • CGI fast. GCI Perl. Ex mod.

What are the (server-side) options? • • • CGI fast. GCI Perl. Ex mod. Perl – Apache web server only. Server extensions: WAI and ISAPI Server-side javascript ASP JSP PHP Cold. Fusion, …

CGI and fast CGI • Expression-processing in Perl makes it a good language to

CGI and fast CGI • Expression-processing in Perl makes it a good language to use for CGI. • CGI has been around a long time. • Client requests for CGI-bin cause the server to run the programs. • Each perl program runs in its own process and its own perl interpreter. • This creates substantial server overhead. • Although fast. CGI does not spawn a new process for every request (just one for each unique program being requested) there is still a lot of overhead.

Server extensions: WAI and ISAPI • Using these you can extend the basic functionality

Server extensions: WAI and ISAPI • Using these you can extend the basic functionality of the server. • The extensions exist inside the main server process. • These use linked C or C++ and run very fast. • But – they are difficult to develop and maintain, and a problem with one can bring down the server. • Proprietary extensions are tied to the server API and possibly OS for which they were developed.

ASP and Server-side javascript • MS developed ASP which allows code snippets in VBScript

ASP and Server-side javascript • MS developed ASP which allows code snippets in VBScript or Javascript or other languages to be inserted into HTML creating dynamic web pages. The code is read and executed by the server before being sent to the client. COM components provide support for ASP can be installed on non-windows platforms from 3 rd party vendors (like Chili!Soft) but such ASP installations will not have the COM library support. ASP is essentially MS -proprietary. • i. Planet/Netscape has developed server-side scripting called server-side javascript. SSJS allows snippets of code to be inserted into html to create active content. SSJS uses javascript as the script language. Support for SSJS is provided only by i. Planet/Netscape.

JSP • JSP are discussed elsewhere and we’ll probably write some, even if just

JSP • JSP are discussed elsewhere and we’ll probably write some, even if just for hw. • These are compiled into servlets, so the servlet container is needed to support these. • The compilation process does create some overhead. This can be mitigated if the jsp are (pre-)compiled at server start-up. • JSP are a better was to present “mostly” html content to the client than servlets. They provide a mechanism for inserting java code as the scripting element into html, much as ASP used VBScript.

SERVLETS • JSP specification is based on servlet specification (recall JSP are compiled into

SERVLETS • JSP specification is based on servlet specification (recall JSP are compiled into servlets). And JSP are often combined with servlets in a web app. • Like CGI, NSAPI and ISAPI, servlets add new functionality to a server. They are written in java and can run on any system with a JRE, (but will need a servlet container!) • Servlets can take advantage of other java technologies: JDBC, JNDI, RMI and so on. • Servlets execute as individual threads and reside in the server web app until it is shut down. (Recall CGI generates a new thread for each request). • Servlet apps are scalable. • Java is more robust than Perl or C++.

Servlet containers • This is the connection between the web server and the servlets.

Servlet containers • This is the connection between the web server and the servlets. It provides a runtime environment, loads and invokes servlets. • Some containers are addons or plugins and provide servlet support if the server doesn’t have it (like Apache or IIS). Containers can be standalone servers or embedded. • The servlet container maps the request to a servlet handling this URI. The container must also convert the servlet response into an http response and return it to the client.

Servlet contexts and web apps • A java web app may consist of JSP,

Servlet contexts and web apps • A java web app may consist of JSP, servlets, applets, static html, custom tag libraries and other java classes. Containers compliant with Servlet 2. 2 specifications provide a standard portable resource packaging mechanism and a web app deployment descriptor describing how the resources fit together. • All these files are arranged in a pre-defined file hierarchy (and may be packaged as a web-archive file. This is an archived file, built using the jar utility but having a. war extension. ) • They may be arranged in the requisite hierarchical structure within the Webapps directory and are automatically deployed on startup by the server. • Each web app is represented by a servlet context associated with a unique URI path prefix called the context path. • The various contexts are hermetic. A context can hold objects shared by other components of the web app, like DB connections. • These specifications are also applied to JSP

Servlet directory structures • In the webapps directory of jakarta/tomcat create a directory for

Servlet directory structures • In the webapps directory of jakarta/tomcat create a directory for your work, let’s say you call it My. Stuff • Create 2 directories, servlets and web-inf under My. Stuff. • In servlets, you will put all your servlet. html files. • In web-inf you will place web. xml (your servlet information file) and a directory called classes, where you’ll place the servlet. class files.

Directory Structure Jakarta/tomcat Webapps ROOT Other directories myexamples Servlets- put html in here Web-inf

Directory Structure Jakarta/tomcat Webapps ROOT Other directories myexamples Servlets- put html in here Web-inf web. xml Classes- put the. class files in here

web-inf • The files in web-inf are not served to the client, they are

web-inf • The files in web-inf are not served to the client, they are classes and configuration information for the web app. Web-inf/ classes contains class files. Web-inf lib contains class files stored as jar files (java-archive) • Web. xml in web-inf is a deployment descriptor. It contains configuration information about the web app in which it resides. • Hunter’s book contains the full DTD for web. xml in appendix C.

HTTP and servlet basics (Chapter 2 of Hunter) • A web application is an

HTTP and servlet basics (Chapter 2 of Hunter) • A web application is an application running on a server accessible via a thin client, like a browser. (Client might also be PDA, cell phone, …) • HTTP defines the way clients and servers communicate.

The HTTP request/response model • • 1. 2. 3. A client sends a request

The HTTP request/response model • • 1. 2. 3. A client sends a request to a server, the server returns a response corresponding to the requested resource or an error message. Three factors are implied in this model: HTTP is stateless. The server doesn’t remember client (requests) once they’ve been processed. Web applications have trouble providing immediate responses like desktop GUI-based software. The server can’t tell how the request was made: Was a button pressed or a window resized? The server can’t look at the browser history or send the response to a particular window. The server doesn’t know when the user closes the browser.

Requests • A browser requests a particular resource from a particular server via an

Requests • A browser requests a particular resource from a particular server via an HTTP URL: http: //employees. oneonta. edu/higgindm/index. ht ml • The request has the syntax: protocol (http)server name (employees. oneonta. edu)- resource (my home page). • Servers typically listen on port 80. Your tomcat server will listen (by default) on port 8080 as in • http: //csci 345. oneonta. edu: 8080/myexamp les/servlets/Servlet. Directory. html

URL…URI… URN • A URL is a specialized form of a URI, universal resource

URL…URI… URN • A URL is a specialized form of a URI, universal resource identifier. A URN is a universal resource name. HTTP handles only URL refers, generally, to the format above, protocol-server (optional port#)-resource. URI might be used once we are at the server and only the identifier part of the resource is needed.

A request to a server consists of • A request line • A header

A request to a server consists of • A request line • A header • Possibly a request body The request line specifies the method name (like get or post) followed by the URI and protocol version # as in: GET /index. html HTTP/1. 1 A GET request retrieves a resource and it is the default. The header provides additional information the server might use and a message body is only included in certain requests. The request also contains information about character sets, image types, language, type of browser, etc. The requested URI might be a static page, a database record, an executable program.

Response structure • The response consists of a status line, response headers and (optionally)

Response structure • The response consists of a status line, response headers and (optionally) a body. • The status line starts with the protocol, a status code. • The headers indicate date of last modification of the resource. Content-type and length are also included. • The body might be an html page: <html><body> Hello world </body></html>

Request parameters • Besides the URI and headers a request message may contain parameters.

Request parameters • Besides the URI and headers a request message may contain parameters. A parameter might be a zip code submitted to weather. com. They can be tacked on to the URI as a query string or included in the body. A query string starts with ‘? ’ and consists of name/value pairs separated by ‘&’. Characters may need special encoding so they are not confused with URI and meta characters.

Request methods • GET and POST are the most common methods. POST requests some

Request methods • GET and POST are the most common methods. POST requests some processing on the server like updating a database or processing an order. • A GET uses a query string for parameters and a POST puts them in the request body. • An html form tag allows GET or POST method to be specified. • A GET request can easily be saved and reloaded, a POST cannot.

Get vs Post • A get operation “gets” information. It is like reading from

Get vs Post • A get operation “gets” information. It is like reading from a bulletin board. It is the default. • A post operation may “post” information to the server. • Get operations may have only limited allowable length (for parameters). • Post operations generally allow transfer of a lot of data.

Get vs Post: Which method should you use? • In fact it doesn’t matter

Get vs Post: Which method should you use? • In fact it doesn’t matter much and a call to do. Post() could even simply call do. Get() in its body or visa versa. • But a get can be bookmarked and server security prohibits saving of data from a post, so you should not generally use a get to do post operations (save to a database, eg. )

Other methods • OPTIONS- what options are available for this URI? • HEAD- send

Other methods • OPTIONS- what options are available for this URI? • HEAD- send all headers generated by GET • PUT- store message body on the server as a resource accessible via the URI • DELETE: delete this URI • TRACE: return request as response body to test communication between client and server.

Javax. servlet. Servlet and HTTPServlet and Generic. Servlet • Every servlet must implement javax.

Javax. servlet. Servlet and HTTPServlet and Generic. Servlet • Every servlet must implement javax. servlet. Servlet • Most do this by implementing either the Generic. Servlet (javax. servlet. Generic. Servlet) or HTTPServlet (javax. servlet. http. Http. Servlet) interface. • Like Applets, servlets have no main() method. The server invokes servlet methods to handle a request just as a browser invokes applet methods (start, init, etc). • When a servlet is dispatched its service() method is called.

More servlet basics • A Generic. Servlet should override its service() method. This method

More servlet basics • A Generic. Servlet should override its service() method. This method gets a request and a response object as parameters. • An Http Servlet overrides either do. Get() or do. Post() methods, or both. HTTP Servlet service() method handles dispatching to a do. XXX() method and should not be overridden.

Other methods • HTTP servlet can override do. Put() and do. Delete() but do.

Other methods • HTTP servlet can override do. Put() and do. Delete() but do. Trace() and do. Options() are handled by default (server) implementations.

Hello world servlet import java. io. *; import javax. servlet. http. *; public class

Hello world servlet import java. io. *; import javax. servlet. http. *; public class Hello. World extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); out. println("<HTML>"); out. println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out. println("<BODY>"); out. println("<BIG>Hello World</BIG>"); out. println("</BODY></HTML>"); } }

API remark • Java API: http: //java. sun. com/j 2 se/1. 5. 0/docs/api/ •

API remark • Java API: http: //java. sun. com/j 2 se/1. 5. 0/docs/api/ • Print. Writer extends Writer and can write String, boolean, double, float, int, char[], and even an object. It also has flush() and close() methods. It can be formatted with a format string.

About Hello World servlet • Page generation: refers to servlets which write an html

About Hello World servlet • Page generation: refers to servlets which write an html page by sending <html>…</html> to the response writer (see above: response. get. Writer() etc) • In webapp design, this may not prove to be a good separation of service delivery, since any GUI upgrade or change will also involve changes to your processing (server -side) code.

deployment • You’ll need to compile servlets, which you can do anywhere, but you’ll

deployment • You’ll need to compile servlets, which you can do anywhere, but you’ll need the javax. servlet classes which come with Tomcat so you can do your compilation there. • Server_root/lib/servlet. jar contains the servlet stuff. • You’ll need to set classpaths properly to get compiles to work. • I just copied javax. servlet to my java/bin and do compiling there.

To run the example(s) • Place the class file as per above, in tomcat/webapps/…web-inf/classes

To run the example(s) • Place the class file as per above, in tomcat/webapps/…web-inf/classes directory • You’ll have to edit the web. xml deployment info that the server uses which is also in the web-inf directory. • If there is an html file that calls the servlet you’ll need to place that in the servlet directory under your webapp directory.

about xml in general and web. xml • XML files may have a required

about xml in general and web. xml • XML files may have a required format – some have a document type description or dtd. Some have a schema, which is itself an xml. XML files can be validated against their format and some processors may reject poorly formed XML. • web. xml conforms to a DTD. You can find the DTD (or schema) for this in Hunter’s book’s appendices. Tomcat will not successfully deploy your servlets if you foul up the web. xml format. • Our Core Servlets covers this material starting on page 60.

Sample web. xml <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE web-app PUBLIC "-//Sun

Sample web. xml <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc. //DTD Web Application 2. 2//EN" "http: //java. sun. com/j 2 ee/dtds/web-app_2_2. dtd"> <web-app> <servlet-name> hi </servlet-name> <servlet-class> Hello. World </servlet-class> </servlet> <servlet-mapping> <servlet-name> hi </servlet-name> <url-pattern> /hello. html </url-pattern> </servlet-mapping> </web-app>

Development tools • I have a zip file containing some useful tools. • It

Development tools • I have a zip file containing some useful tools. • It contains a class called Servlet Server. Unfortunately it is compiled with 1. 4 java, so you’ll have to point it to a 1. 4 jre in order to get it to work. • It is useful only for testing, not deployment.

Batch file for Servlet. Server set path=c: compilersj 2 sdk 1. 4. 1_01bin set

Batch file for Servlet. Server set path=c: compilersj 2 sdk 1. 4. 1_01bin set jdkhome=c: compilersj 2 sdk 1. 4. 1_01bin set classpath=c: compilersj 2 sdk 1. 4. 1_01bin; p: classes; c: compilersj 2 sdk 1. 4. 1_01lib p: classes cd p: classes p: : start /wait /Dp: classes java Servlet. Server goto start

DOS window for batch file P: classes>set path=c: compilersj 2 sdk 1. 4. 1_01bin

DOS window for batch file P: classes>set path=c: compilersj 2 sdk 1. 4. 1_01bin P: classes>set jdkhome=c: compilersj 2 sdk 1. 4. 1_01bin P: classes>set classpath=c: compilersj 2 sdk 1. 4. 1_01bin; p: classes; c: compi lersj 2 sdk 1. 4. 1_01lib P: classes>p: classes 'p: classes' is not recognized as an internal or external command, operable program or batch file. P: classes>cd p: classes P: classes>p: P: classes>start /wait /Dp: classes java Servlet. Server

DOS window for server

DOS window for server

More about Servlet. Server • This is a mini server for testing servlets. Like

More about Servlet. Server • This is a mini server for testing servlets. Like Tomcat, it listens at port 8080 (so you can’t run both at the same time without changing default port number). • It has no interface or configuration or deployment settings. • You can test a servlet by running it directly. • It does not load html. • (These files are on my p drive. )

Servlet. Server • It is a pain in the neck to have two java

Servlet. Server • It is a pain in the neck to have two java versions and to try to remember which one to use but Servlet. Server does provide a nicer way to test your servlets than having to complete deployment using web. xml in Tomcat. • You can use the default servlet context and this sidesteps editing web. xml. This solution is for development (or classroom) use only, not for production.

Servlet 1. java source (similar to Hello. World) import javax. servlet. *; import javax.

Servlet 1. java source (similar to Hello. World) import javax. servlet. *; import javax. servlet. http. *; import java. io. *; import java. util. *; public class Servlet 1 extends Http. Servlet { //Initialize global variables public void init(Servlet. Config config) throws Servlet. Exception { super. init(config); } //Process the HTTP Get request public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Print. Writer out = new Print. Writer (response. get. Output. Stream()); out. println("<html>"); out. println("<head><title>Servlet 1</title></head>"); out. println("<body>"); out. println("Hello World. . . Servlet 1 is running!"); out. println("</body></html>"); out. close(); } //Process the HTTP Post request public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(request, response); } //Get Servlet information public String get. Servlet. Info() { return "untitled 3. Servlet 1 Information"; } }

Running Servlet 1

Running Servlet 1

com. oreilly. servlet. *. class files • You can download utility classes used in

com. oreilly. servlet. *. class files • You can download utility classes used in the text in addition to the text examples, and you’ll need them to run some of the examples. • These can be found at the book’s website. • You’ll need to save them in their package hierarchical structure. (as per the heading above)

Here’s my p: classescomoreillyservlet directory (copied after I unzipped download)

Here’s my p: classescomoreillyservlet directory (copied after I unzipped download)

A form whose Get action runs a servlet <HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY> <FORM

A form whose Get action runs a servlet <HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY> <FORM METHOD=GET ACTION="http: //csci 345. oneonta. edu: 8080/servlet/Hello"> If you don't mind me asking, what is your name? <INPUT TYPE=TEXT NAME="name"><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

In IE

In IE

The servlet import java. io. *; import javax. servlet. http. *; public class Hello

The servlet import java. io. *; import javax. servlet. http. *; public class Hello extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); String name = req. get. Parameter("name"); out. println("<HTML>"); out. println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out. println("<BODY>"); out. println("Hello, " + name); out. println("</BODY></HTML>"); } public String get. Servlet. Info() { return "A servlet that knows the name of the person to whom it's" + "saying hello"; } }

In IE

In IE

servlet which pastes in a name import java. io. *; import javax. servlet. http.

servlet which pastes in a name import java. io. *; import javax. servlet. http. *; public class Hello extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); String name = req. get. Parameter("name"); out. println("<HTML>"); out. println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out. println("<BODY>"); out. println("Hello, " + name); out. println("</BODY></HTML>"); } public String get. Servlet. Info() { return "A servlet that knows the name of the person to whom it's" + "saying hello"; }}

Handling post request via do. Get() method • If a form had: <FORM METHOD=POST

Handling post request via do. Get() method • If a form had: <FORM METHOD=POST ACTION=“servlets/Hello”> • The servlet could provide a post method which simply called get: public void do. Post(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException{ do. Get(req, res); }

Modifying form & Hello servlet to handle Post request <HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY>

Modifying form & Hello servlet to handle Post request <HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY> <FORM METHOD=POST ACTION="http: //localhost: 8080/servlet/Hello"> If you don't mind me asking, what is your name? <INPUT TYPE=TEXT NAME="name"><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

Modifying Hello to handle Post

Modifying Hello to handle Post

Form & servlet with post action import java. io. *; import javax. servlet. http.

Form & servlet with post action import java. io. *; import javax. servlet. http. *; public class Hello extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); String name = req. get. Parameter("name"); out. println("<HTML>"); out. println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out. println("<BODY>"); out. println("Hello, " + name); out. println("</BODY></HTML>"); } public void do. Post(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { do. Get(req, res); } public String get. Servlet. Info() { return "A servlet that knows the name of the person to whom it's" + "saying hello"; } }

Handling head-only requests import java. io. *; import javax. servlet. http. *; public class

Handling head-only requests import java. io. *; import javax. servlet. http. *; public class Hello. World extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); if(req. get. Method(). equals(“HEAD”))return; //leave after setting head info Print. Writer out = res. get. Writer(); out. println("<HTML>"); out. println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out. println("<BODY>"); out. println("<BIG>Hello World</BIG>"); out. println("</BODY></HTML>"); } }

A few variations of welcome servlet posted at: • http: //csci 345. oneonta. edu:

A few variations of welcome servlet posted at: • http: //csci 345. oneonta. edu: 8080/myexamples/servlets/Welcome. Ser vlet. html • http: //csci 345. oneonta. edu: 8080/myexamples/servlets/Welcome. Ser vlet 2 B. html • http: //csci 345. oneonta. edu: 8080/myexamples/servlets/Welcome. Ser vlet 3. html • http: //csci 345. oneonta. edu: 8080/myexamples/servlets/Welcome. Ser vlet 4. html