Servlets Introduction Networking Massive complex topic Java networking

  • Slides: 71
Download presentation
Servlets

Servlets

Introduction • Networking – Massive, complex topic – Java networking in several packages •

Introduction • Networking – Massive, complex topic – Java networking in several packages • java. net – Socket based communications • View networking as streams of data – Reading/writing to socket like reading/writing to file – Packet based communications • Transmit packets of information. • Remote Method Invocation (RMI) – Objects in different Java Virtual Machines can communicate

Introduction • Client-server relationship – Client request action – Server performs action, responds to

Introduction • Client-server relationship – Client request action – Server performs action, responds to client – This view foundation of servlets • Highest-level view of networking • Servlet extends functionality of server – Useful for database-intensive applications • Thin clients - little client-side support needed • Server controls database access – Logic code written once, on server

Overview of Servlet Technology • Servlets – Analog to applets • Execute on server's

Overview of Servlet Technology • Servlets – Analog to applets • Execute on server's machine, supported by most web servers – Demonstrate communication via HTTP protocol • Client sends HTTP request • Server receives request, servlets process it • Results returned (HTML document, images, binary data)

The Servlet API • Servlet interface – Implemented by all servlets – Many methods

The Servlet API • Servlet interface – Implemented by all servlets – Many methods invoked automatically by server • Similar to applets (paint, init, start, etc. ) – abstract classes that implement Servlet • Generic. Servlet (javax. servlet) • HTTPServlet (javax. servlet. http) – Examples in chapter extend HTTPServlet • Methods – void init( Servlet. Config config ) • Automatically called, argument provided

The Servlet API • Methods – Servlet. Config get. Servlet. Config() • Returns reference

The Servlet API • Methods – Servlet. Config get. Servlet. Config() • Returns reference to object, gives access to config info – void service ( Servlet. Request request, Servlet. Response response ) • Key method in all servlets • Provide access to input and output streams – Read from and send to client – void destroy() • Cleanup method, called when servlet exiting

Life Cycle of Servlet servlet Http. Servlet Generic. Servlet init(Servlet. Config); service(Servlet. Request, Servlet.

Life Cycle of Servlet servlet Http. Servlet Generic. Servlet init(Servlet. Config); service(Servlet. Request, Servlet. Response); do. Get(Http. Servlet. Request, Http. Servlet. Response); do. Post(Http. Servlet. Request, Http. Servlet. Response); destroy(); …….

Http. Servlet Class • Http. Servlet – Base class for web-based servlets – Overrides

Http. Servlet Class • Http. Servlet – Base class for web-based servlets – Overrides method service • Request methods: – GET - retrieve HTML documents or image – POST - send server data from HTML form – Methods do. Get and do. Post respond to GET and POST • Called by service • Receive Http. Servlet. Request and Http. Servlet. Response (return void) objects

Http. Servlet. Request Interface • Http. Servlet. Request interface – Object passed to do.

Http. Servlet. Request Interface • Http. Servlet. Request interface – Object passed to do. Get and do. Post – Extends Servlet. Request • Methods – String get. Parameter( String name ) • Returns value of parameter name (part of GET or POST) – Enumeration get. Parameter. Names() • Returns names of parameters (POST) – String[] get. Parameter. Values( String name ) • Returns array of strings containing values of a parameter – Cookie[] get. Cookies() • Returns array of Cookie objects, can be used to identify client

Http. Servlet. Response Interface • Http. Servlet. Response – Object passed to do. Get

Http. Servlet. Response Interface • Http. Servlet. Response – Object passed to do. Get and do. Post – Extends Servlet. Response • Methods – void add. Cookie( Cookie cookie ) • Add Cookie to header of response to client – Servlet. Output. Stream get. Output. Stream() • Gets byte-based output stream, send binary data to client – Print. Writer get. Writer() • Gets character-based output stream, send text to client – void set. Content. Type( String type ) • Specify MIME type of the response (Multipurpose Internet Mail Extensions) • MIME type “text/html” indicates that response is HTML document. • Helps display data

Handling HTTP GET Requests • HTTP GET requests – Usually gets content of specified

Handling HTTP GET Requests • HTTP GET requests – Usually gets content of specified URL • Usually HTML document (web page) • Example servlet – Handles HTTP GET requests – User clicks Get Page button in HTML document • GET request sent to servlet HTTPGet. Servlet – Servlet dynamically creates HTML document displaying "Welcome to Servlets!"

Handling HTTP GET Requests 3 import javax. servlet. *; 4 import javax. servlet. http.

Handling HTTP GET Requests 3 import javax. servlet. *; 4 import javax. servlet. http. *; – Use data types from javax. servlet and javax. servlet. http 7 public class HTTPGet. Servlet extends Http. Servlet { – Http. Servlet has useful methods, inherit from it 8 public void do. Get( Http. Servlet. Request request, 9 Http. Servlet. Response response ) 10 throws Servlet. Exception, IOException – Method do. Get • • Responds to GET requests Default action: BAD_REQUEST error (file not found) Override for custom GET processing Arguments represent client request and server response

Handling HTTP GET Requests 14 response. set. Content. Type( "text/html" ); // content type

Handling HTTP GET Requests 14 response. set. Content. Type( "text/html" ); // content type – set. Content. Type • Specify content • text/html for HTML documents 12 Print. Writer output; 15 output = response. get. Writer(); // get writer – get. Writer • Returns Print. Writer object, can send text to client • get. Output. Stream to send binary data (returns Servlet. Output. Stream object)

Handling HTTP GET Requests 19 buf. append( "<HTML><HEAD><TITLE>n" ); 20 buf. append( "A Simple

Handling HTTP GET Requests 19 buf. append( "<HTML><HEAD><TITLE>n" ); 20 buf. append( "A Simple Servlet Examplen" ); 21 buf. append( "</TITLE></HEAD><BODY>n" ); 22 buf. append( "<H 1>Welcome to Servlets!</H 1>n" ); 23 buf. append( "</BODY></HTML>" ); – Lines 19 -23 create HTML document 24 output. println( buf. to. String() ); 25 output. close(); // close Print. Writer stream • println sends response to client • close terminates output stream – Flushes buffer, sends info to client

Handling HTTP GET Requests • Running servlets – Must be running on a server

Handling HTTP GET Requests • Running servlets – Must be running on a server • Check documentation for how to install servlets • Tomcat web server • Apache Tomcat

Handling HTTP GET Requests • Port number – Where server waits for client (handshake

Handling HTTP GET Requests • Port number – Where server waits for client (handshake point) – Client must specify proper port number • Integers 1 - 65535, 1024 and below usually reserved – Well-known port numbers • Web servers - port 80 default • JSDK/Apache Tomcat 4. 0 Webserver- port 8080 – Change in default. cfg (server. port=8080)

Handling HTTP GET Requests • HTML documents 1 2 3 4 5 6 7

Handling HTTP GET Requests • HTML documents 1 2 3 4 5 6 7 <!-- Fig. 19. 6: HTTPGet. Servlet. html --> <HTML> <HEAD> <TITLE> Servlet HTTP GET Example </TITLE> </HEAD> – Comments: <!-- text --> – Tags: <TAG>. . . </TAG> • <HTML>. . . <HTML> tags enclose document • <HEAD>. . . </HEAD> - enclose header – Includes <TITLE> Title </TITLE> tags – Sets title of document

Handling HTTP GET Requests 9 10 11 12 13 14 15 16 <FORM ACTION="http:

Handling HTTP GET Requests 9 10 11 12 13 14 15 16 <FORM ACTION="http: //lab. cs. siu. edu: 8080/rahimi/HTTPGet. Servlet" METHOD="GET"> <P>Click the button to have the servlet send an HTML document</P> <INPUT TYPE="submit" VALUE="Get HTML Document"> </FORM> </BODY> – Document body (<BODY> tags) • Has literal text and tags formatting – Form (<FORM> tags ) • ACTION - server-side form handler • METHOD - request type

Handling HTTP GET Requests 10 ACTION="http: //localhost: 8080/servlet/HTTPGet. Servlet" – ACTION • localhost -

Handling HTTP GET Requests 10 ACTION="http: //localhost: 8080/servlet/HTTPGet. Servlet" – ACTION • localhost - your computer • : 8080 - port • /servlet - directory 14 <INPUT TYPE="submit" VALUE="Get HTML Document"> – GUI component • INPUT element • TYPE - "submit" (button) • VALUE - label • When pressed, performs ACTION • If parameters passed, separated by ? in URL

1 // Fig. 19. 5: HTTPGet. Servlet. java 2 // Creating and sending a

1 // Fig. 19. 5: HTTPGet. Servlet. java 2 // Creating and sending a page to the client 3 import javax. servlet. *; 4 import javax. servlet. http. *; 5 import java. io. *; Import necessary classes and inherit 1. import methods from Http. Servlet. 6 1. 1 extends Http. Servlet 7 public class HTTPGet. Servlet extends Http. Servlet { 8 public void do. Get( Http. Servlet. Request request, 9 Http. Servlet. Response response ) 10 throws Servlet. Exception, IOException 2. do. Get 11 { 12 Print. Writer output; 2. 1 set. Content. Type 13 14 response. set. Content. Type( "text/html" ); // content type 15 output = response. get. Writer(); // get writer 16 17 // create and send HTML page to client 18 String. Buffer buf = new String. Buffer(); 19 buf. append( "<HTML><HEAD><TITLE>n" ); 20 buf. append( "A Simple Servlet Examplen" ); 21 buf. append( "</TITLE></HEAD><BODY>n" ); 22 buf. append( "<H 1>Welcome to Servlets!</H 1>n" ); 23 buf. append( "</BODY></HTML>" ); 24 output. println( buf. to. String() ); 25 output. close(); // close Print. Writer stream 26 } 27 } 2. 2 get. Writer Create Print. Writer object. 2. 3 and println Create HTML file send to client.

1 <!-- Fig. 19. 6: HTTPGet. Servlet. html --> 2 <HTML> 3 <HEAD> 4

1 <!-- Fig. 19. 6: HTTPGet. Servlet. html --> 2 <HTML> 3 <HEAD> 4 <TITLE> 5 Servlet HTTP GET Example 6 </TITLE> 7 </HEAD> 8 <BODY> 9 <FORM HTML document ACTION specifies form handler, METHOD specifies request type. 1. <TITLE> 10 ACTION="http: //lab. cs. siu. edu: 8080/rahimi/HTTPGet. Servlet" 10 11 METHOD="GET"> 12 <P>Click the button to have the servlet send 2. <FORM> 2. 1 ACTION 13 an HTML document</P> 14 <INPUT TYPE="submit" VALUE="Get HTML Document"> 2. 2 METHOD 15 </FORM> 16 </BODY> 17 </HTML> Creates submit button, performs ACTION when clicked. 3. INPUT TYPE

Program Output

Program Output

Handling HTTP POST Requests • HTTP POST – Used to post data to server-side

Handling HTTP POST Requests • HTTP POST – Used to post data to server-side form handler (i. e. surveys) – Both GET and POST can supply parameters • Example servlet – Survey • Store results in file on server – User selects radio button, presses Submit • Browser sends POST request to servlet – Servlet updates responses • Displays cumulative results

Handling HTTP POST Requests 9 public class HTTPPost. Servlet extends Http. Servlet { –

Handling HTTP POST Requests 9 public class HTTPPost. Servlet extends Http. Servlet { – Extend Http. Servlet • Handle GET and POST 10 private String animal. Names[] = 11 { "dog", "cat", "bird", "snake", "none" }; – Array for animal names 13 public void do. Post( Http. Servlet. Request request, 14 Http. Servlet. Response response ) 15 throws Servlet. Exception, IOException – do. Post • Responds to POST requests (default BAD_REQUEST) • Same arguments as do. Get (client request, server response)

Handling HTTP POST Requests 18 File f = new File( "survey. txt" ); 23

Handling HTTP POST Requests 18 File f = new File( "survey. txt" ); 23 Object. Input. Stream input = new Object. Input. Stream( 24 new File. Input. Stream( f ) ); 26 animals = (int []) input. read. Object(); – Open survey. txt, load animals array 40 String value = 41 request. get. Parameter( "animal" ); – Method get. Parameter( name ) • Returns value of parameter as a string 64 response. set. Content. Type( "text/html" ); // content type – Content type

Handling HTTP POST Requests 67 String. Buffer buf = new String. Buffer(); 68 buf.

Handling HTTP POST Requests 67 String. Buffer buf = new String. Buffer(); 68 buf. append( "<html>n" ); 69 buf. append( "<title>Thank you!</title>n" ); 70 buf. append( "Thank you for participating. n" ); 71 73 74 75 76 88 buf. append( "<BR>Results: n<PRE>" ); Decimal. Format two. Digits = new Decimal. Format( "#0. 00" ); for ( int i = 0; i < percentages. length; ++i ) { buf. append( "<BR>" ); buf. append( animal. Names[ i ] ); response. Output. println( buf. to. String() ); – Return HTML document as before – <PRE> tag • Preformatted text, fixed-width – <BR> tag - line break

Handling HTTP POST Requests 8 9 10 11 12 13 14 15 16 17

Handling HTTP POST Requests 8 9 10 11 12 13 14 15 16 17 18 <FORM METHOD="POST" ACTION= "http: //lab. cs. siu. edu: 8080/rahimi/HTTPPost. Servlet"> What is your favorite pet? <BR> <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR> <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR> <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR> <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR> <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None <BR><INPUT TYPE=submit VALUE="Submit"> <INPUT TYPE=reset> </FORM> – METHOD="POST" – Radio buttons (only one may be selected) • TYPE - radio • NAME - parameter name • VALUE - parameter value • CHECKED - initially selected

Handling HTTP POST Requests 8 9 10 11 12 13 14 15 16 17

Handling HTTP POST Requests 8 9 10 11 12 13 14 15 16 17 18 <FORM METHOD="POST" ACTION= "http: //lab. cs. siu. edu: 8080/rahimi/HTTPPost. Servlet"> What is your favorite pet? <BR> <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR> <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR> <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR> <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR> <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None <BR><INPUT TYPE=submit VALUE="Submit"> <INPUT TYPE=reset> </FORM> – Submit button (executes ACTION) – Reset button - browser resets form, with None selected

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Fig. 19. 7: HTTPPost. Servlet. java // A simple survey servlet import javax. servlet. *; import javax. servlet. http. *; import java. text. *; import java. io. *; import java. util. *; Extending Http. Servlet allows processing of GET POST 1. and import requests. public class HTTPPost. Servlet extends Http. Servlet { private String animal. Names[] = { "dog", "cat", "bird", "snake", "none" }; public void do. Post( Http. Servlet. Request request, Http. Servlet. Response response ) throws Servlet. Exception, IOException { int animals[] = null, total = 0; File f = new File( "survey. txt" ); if ( f. exists() ) { // Determine # of survey responses so far try { Object. Input. Stream input = new Object. Input. Stream( new File. Input. Stream( f ) ); animals = (int []) input. read. Object(); input. close(); // close stream for ( int i = 0; i < animals. length; ++i ) total += animals[ i ]; } 1. 1 extends Http. Servlet 1. 2 animal. Names 2. do. Post 2. 1 Open file

32 33 34 35 36 37 38 39 40 41 42 43 44 45

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 catch( Class. Not. Found. Exception cnfe ) { cnfe. print. Stack. Trace(); } Use request (Http. Servlet. Request) method } get. Parameter to get value of animal. else 2. 2 get. Parameter animals = new int[ 5 ]; // read current survey response String value = request. get. Parameter( "animal" ); ++total; // update total of all responses // determine which was selected and update its total for ( int i = 0; i < animal. Names. length; ++i ) if ( value. equals( animal. Names[ i ] ) ) ++animals[ i ]; // write updated totals out to disk Object. Output. Stream output = new Object. Output. Stream( new File. Output. Stream( f ) ); output. write. Object( animals ); output. flush(); output. close(); // Calculate percentages double percentages[] = new double[ animals. length ]; for ( int i = 0; i < percentages. length; ++i ) percentages[ i ] = 100. 0 * animals[ i ] / total; 2. 3 Write to file

63 64 65 66 67 68 69 70 71 72 73 74 75 76

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 // send a thank you message to client response. set. Content. Type( "text/html" ); // content type Print. Writer response. Output = response. get. Writer(); String. Buffer buf = new String. Buffer(); buf. append( "<html>n" ); buf. append( "<title>Thank you!</title>n" ); buf. append( "Thank you for participating. n" ); buf. append( "<BR>Results: n<PRE>" ); Decimal. Format two. Digits = new Decimal. Format( "#0. 00" ); for ( int i = 0; i < percentages. length; ++i ) { buf. append( "<BR>" ); buf. append( animal. Names[ i ] ); buf. append( ": " ); buf. append( two. Digits. format( percentages[ i ] ) ); buf. append( "% responses: " ); buf. append( animals[ i ] ); buf. append( "n" ); } buf. append( "n<BR>Total responses: " ); buf. append( total ); buf. append( "</PRE>n</html>" ); response. Output. println( buf. to. String() ); response. Output. close(); } } 2. 4 get. Writer 2. 5 Create HTML code 2. 6 println

1 <!-- Fig. 19. 8: HTTPPost. Servlet. html --> 2 <HTML> 3 <HEAD> 4

1 <!-- Fig. 19. 8: HTTPPost. Servlet. html --> 2 <HTML> 3 <HEAD> 4 <TITLE>Servlet HTTP Post Example</TITLE> 5 </HEAD> 6 7 Use a POST request type. <BODY> 8 <FORM METHOD="POST" ACTION= 9 "http: //lab. cs. siu. edu: 8080/rahimi/HTTPPost. Servlet"> 10 What is your favorite pet? <BR> HTML file 1. <FORM> 1. 1 METHOD="POST" 11 <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR> 12 <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR> 13 <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR> 2. <INPUT> 14 <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR> 15 <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None 16 <BR><INPUT TYPE=submit VALUE="Submit"> 17 <INPUT TYPE=reset> 18 </FORM> 19 </BODY> 20 </HTML> Returns form to original state (None selected). Create radio buttons. Specify parameter name and value. None is initially selected (CHECKED).

Program Output

Program Output

Program Output

Program Output

Session Tracking • Web sites – Many have custom web pages/functionality • Custom home

Session Tracking • Web sites – Many have custom web pages/functionality • Custom home pages - http: //my. yahoo. com/ • Shopping carts • Marketing – HTTP protocol does not support persistent information • Cannot distinguish clients • Distinguishing clients – Cookies – Session Tracking

Cookies • Cookies – Small files that store information on client's computer – Servlet

Cookies • Cookies – Small files that store information on client's computer – Servlet can check previous cookies for information • Header – In every HTTP client-server interaction – Contains information about request (GET or POST) and cookies stored on client machine – Response header includes cookies servers wants to store • Age – Cookies have a lifespan – Can set maximum age • Cookies can expire and are deleted

Cookies • Example – Demonstrate cookies – Servlet handles both POST and GET requests

Cookies • Example – Demonstrate cookies – Servlet handles both POST and GET requests – User selects programming language (radio buttons) • POST - Add cookie containing language, return HTML page • GET - Browser sends cookies to servlet – Servlet returns HTML document with recommended books – Two separate HTML files • One invokes POST, the other GET • Same ACTION - invoke same servlet

Cookies 14 public void do. Post( Http. Servlet. Request request, 15 Http. Servlet. Response

Cookies 14 public void do. Post( Http. Servlet. Request request, 15 Http. Servlet. Response response ) 19 String language = request. get. Parameter( "lang" ); – Method do. Post • Get language selection 21 Cookie c = new Cookie( language, get. ISBN( language ) ); 22 c. set. Max. Age( 120 ); // seconds until cookie removed – Cookie constructor • Cookie ( name, value ) • get. ISBN is utility method • set. Max. Age( seconds ) - deleted when expire

Cookies 23 response. add. Cookie( c ); // must precede get. Writer – Add

Cookies 23 response. add. Cookie( c ); // must precede get. Writer – Add cookie to client response • Part of HTTP header, must come first • Then HTML document sent to client 41 public void do. Get( Http. Servlet. Request request, 42 Http. Servlet. Response response ) 46 Cookie cookies[]; 48 cookies = request. get. Cookies(); // get client's cookies – Method do. Get – get. Cookies • Returns array of Cookies

Cookies 57 62 63 64 if ( cookies != null ) { output. println(

Cookies 57 62 63 64 if ( cookies != null ) { output. println( cookies[ i ]. get. Name() + " How to Program. " + "ISBN#: " + cookies[ i ]. get. Value() + "<BR>" ); – Cookie methods • get. Name, get. Value • Used to determine recommended book • If cookie has expired, does not execute

1 // Fig. 19. 9: Cookie. Example. java 2 // Using cookies. 3 import

1 // Fig. 19. 9: Cookie. Example. java 2 // Using cookies. 3 import javax. servlet. *; 4 import javax. servlet. http. *; 5 import java. io. *; Allows class to handle GET and POST. 1. import 6 1. 1 extends Http. Servlet 7 public class Cookie. Example extends Http. Servlet { 8 private String names[] = { "C", "C++", "Java", 9 "Visual Basic 6" }; 10 private String isbn[] = { 2. do. Post 11 "0 -13 -226119 -7", "0 -13 -528910 -6", 12 "0 -13 -012507 -5", "0 -13 -528910 -6" }; 2. 1 get. Parameter 13 14 public void do. Post( Http. Servlet. Request request, 15 Http. Servlet. Response response ) Create a new Cookie, initialized 16 throws Servlet. Exception, IOException with language parameter. 2. 2 Cookie 17 { 2. 3 set. Max. Age 18 Print. Writer output; 19 String language = request. get. Parameter( "lang" ); 20 21 Cookie c = new Cookie( language, get. ISBN( language ) ); 2. 4 add. Cookie 22 c. set. Max. Age( 120 ); // seconds until cookie removed 23 response. add. Cookie( c ); // must precede get. Writer 24 25 response. set. Content. Type( "text/html" ); 26 output = response. get. Writer(); 27 Set maximum age of cookie, add to header.

28 29 30 31 32 33 34 35 36 37 38 39 40 41

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // send HTML page to client output. println( "<HTML><HEAD><TITLE>" ); output. println( "Cookies" ); output. println( "</TITLE></HEAD><BODY>" ); output. println( "<P>Welcome to Cookies!<BR>" ); output. println( "<P>" ); output. println( language ); output. println( " is a great language. " ); output. println( "</BODY></HTML>" ); output. close(); // close stream } public void do. Get( Http. Servlet. Request request, Http. Servlet. Response response ) throws Servlet. Exception, IOException { Returns array of Cookies. Print. Writer output; Cookie cookies[]; cookies = request. get. Cookies(); // get client's cookies response. set. Content. Type( "text/html" ); output = response. get. Writer(); output. println( "<HTML><HEAD><TITLE>" ); output. println( "Cookies II" ); output. println( "</TITLE></HEAD><BODY>" ); 3. do. Get 3. 1 get. Cookies

57 58 59 60 61 if ( cookies != null ) { output. println(

57 58 59 60 61 if ( cookies != null ) { output. println( "<H 1>Recommendations</H 1>" ); // get the name of each cookie for ( int i = 0; i < cookies. length; i++ ) 3. 2 get. Name, get. Value 62 output. println( 63 cookies[ i ]. get. Name() + " How to Program. " + 64 "ISBN#: " + cookies[ i ]. get. Value() + "<BR>" ); 4. Method get. ISBN 65 66 67 68 } else { Use cookies to determine output. println( "<H 1>No Recommendations</H 1>" ); recommended book and ISBN. output. println( "You did not select a language or" ); 69 70 71 72 73 74 output. println( "the cookies have expired. " ); } 75 76 77 78 79 80 output. println( "</BODY></HTML>" ); output. close(); // close stream } private String get. ISBN( String lang ) { for ( int i = 0; i < names. length; ++i ) if ( lang. equals( names[ i ] ) ) return isbn[ i ]; 81 82 return ""; // no matching string found 83 } 84 } If cookies have expired, no recommendations.

1 <!-- Fig. 19. 10: Select. Language. html --> 2 <HTML> 3 <HEAD> 4

1 <!-- Fig. 19. 10: Select. Language. html --> 2 <HTML> 3 <HEAD> 4 <TITLE>Cookies</TITLE> 5 </HEAD> 6 <BODY> HTML file 1. POST 7 <FORM ACTION="http: // lab. cs. siu. edu: 8080/rahimi/Cookie. Example" 8 METHOD="POST"> 9 <STRONG>Select a programming language: 10 </STRONG><BR> 11 <PRE> 12 <INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR> 13 <INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR> 14 <INPUT TYPE="radio" NAME="lang" VALUE="Java" 15 CHECKED>Java<BR> 16 <INPUT TYPE="radio" NAME="lang" 17 VALUE="Visual Basic 6">Visual Basic 6 18 </PRE> 19 <INPUT TYPE="submit" VALUE="Submit"> 20 <INPUT TYPE="reset"> </P> 21 </FORM> 22 </BODY> 23 </HTML> 2. Radio buttons

7 1 <!-- Fig. 19. 11: Book. Recommendation. html --> 2 <HTML> 3 <HEAD>

7 1 <!-- Fig. 19. 11: Book. Recommendation. html --> 2 <HTML> 3 <HEAD> 4 <TITLE>Cookies</TITLE> 5 </HEAD> 6 <BODY> <FORM ACTION="http: //lab. cs. siu. edu: 8080/rahimi/Cookie. Example" 8 METHOD="GET"> 9 Press "Recommend books" for a list of books. 10 <INPUT TYPE=submit VALUE="Recommend books"> 11 </FORM> 12 </BODY> 13 </HTML> HTML file 1. GET 2. Submit

Program Output

Program Output

Session Tracking with Http. Session • Http. Session (javax. servlet. http) – Alternative to

Session Tracking with Http. Session • Http. Session (javax. servlet. http) – Alternative to cookies – Data available until browsing ends • Methods – Creation 23 Http. Session session = request. get. Session( true ); – get. Session( create. New ) • Class Http. Servlet. Request • Returns client's previous Http. Session object • create. New - if true, creates new Http. Session object if does not exist

Session Tracking with Http. Session 26 session. put. Value( language, get. ISBN( language )

Session Tracking with Http. Session 26 session. put. Value( language, get. ISBN( language ) ); – putvalue( name, value ) • Adds a name/value pair to object 58 value. Names = session. get. Value. Names(); 73 for ( int i = 0; i < value. Names. length; i++ ) { 74 String value = 75 (String) session. get. Value( value. Names[ i ] ); – get. Value. Names() • Returns array of Strings with names – get. Value( name ) • Returns value of name as an Object • Cast to proper type

Session Tracking with Http. Session • Redo previous example – Use Http. Session instead

Session Tracking with Http. Session • Redo previous example – Use Http. Session instead of cookies – Use same HTML files as before • Change ACTION URL to new servlet

1 // Fig. 19. 13: Session. Example. java 2 // Using sessions. 3 import

1 // Fig. 19. 13: Session. Example. java 2 // Using sessions. 3 import javax. servlet. *; 4 import javax. servlet. http. *; 5 import java. io. *; 1. import 7 public class Session. Example extends Http. Servlet { 2. do. Post 8 private final static String names[] = 9 { "C", "C++", "Java", "Visual Basic 6" }; 6 10 private final static String isbn[] = { 2. 1 get. Session 11 "0 -13 -226119 -7", "0 -13 -528910 -6", 12 "0 -13 -012507 -5", "0 -13 -528910 -6" }; 2. 2 put. Value 13 14 public void do. Post( Http. Servlet. Request request, 15 Http. Servlet. Response response ) 16 throws Servlet. Exception, IOException 17 { 18 Print. Writer output; 19 String language = request. get. Parameter( "lang" ); 20 Load Http. Session if exists, create if does not. 21 // Get the user's session object. 22 // Create a session (true) if one does not exist. 23 Http. Session session = request. get. Session( true ); 24 25 // add a value for user's choice to session 26 session. put. Value( language, get. ISBN( language ) ); 27 Set name/value pair.

28 29 30 31 32 33 34 35 36 37 38 39 40 41

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 response. set. Content. Type( "text/html" ); output = response. get. Writer(); // send HTML page to client output. println( "<HTML><HEAD><TITLE>" ); output. println( "Sessions" ); output. println( "</TITLE></HEAD><BODY>" ); output. println( "<P>Welcome to Sessions!<BR>" ); output. println( "<P>" ); output. println( language ); output. println( " is a great language. " ); output. println( "</BODY></HTML>" ); 3. do. Get 3. 1 get. Session output. close(); // close stream } public void do. Get( Http. Servlet. Request request, Http. Servlet. Response response ) throws Servlet. Exception, IOException Do not create object if does not { exist. session set to null. Print. Writer output; // Get the user's session object. // Don't create a session (false) if one does not exist. Http. Session session = request. get. Session( false ); // get names of session object's values String value. Names[];

57 58 59 60 61 62 63 64 65 66 67 68 69 70

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 if ( session != null ) value. Names = session. get. Value. Names(); else value. Names = null; Put names into array. response. set. Content. Type( "text/html" ); output = response. get. Writer(); 3. 2 get. Value. Names 3. 3 get. Value output. println( "<HTML><HEAD><TITLE>" ); output. println( "Sessions II" ); output. println( "</TITLE></HEAD><BODY>" ); if ( value. Names != null && value. Names. length != 0 ) { output. println( "<H 1>Recommendations</H 1>" ); // get value for each name in value. Names for ( int i = 0; i < value. Names. length; i++ ) { String value = (String) session. get. Value( value. Names[ i ] ); output. println( value. Names[ i ] + " How to Program. " + Get value "ISBN#: " + value + "<BR>" ); } } else { output. println( "<H 1>No Recommendations</H 1>" ); output. println( "You did not select a language or" ); output. println( "the session has expired. " ); } associated with name.

87 88 output. println( "</BODY></HTML>" ); 89 output. close(); // close stream 90 }

87 88 output. println( "</BODY></HTML>" ); 89 output. close(); // close stream 90 } 91 92 private String get. ISBN( String lang ) 93 { 94 for ( int i = 0; i < names. length; ++i ) 95 if ( lang. equals( names[ i ] ) ) 96 return isbn[ i ]; 97 98 return ""; // no matching string found 99 } 100 }

Program Output

Program Output

Program Output

Program Output

Program Output

Program Output

Multitier Applications: Using JDBC from a Servlet • Servlets and databases – Communicate via

Multitier Applications: Using JDBC from a Servlet • Servlets and databases – Communicate via JDBC • Connect to databases in general manner • Use SQL-based queries • Three tier distributed applications – User interface • Often in HTML, sometimes applets • HTML preferred, more portable – Business logic (middle tier) • Accesses database – Database access – Three tiers may be on separate computers • Web servers for middle tier

Multitier Applications: Using JDBC from a Servlet • Servlets – Method init • Called

Multitier Applications: Using JDBC from a Servlet • Servlets – Method init • Called exactly once, before client requests • Initialization parameters – Method destroy • Called automatically, cleanup method • Close files, connections to databases, etc.

Multitier Applications: Using JDBC from a Servlet • HTML files – <INPUT TYPE=CHECKBOX NAME=name

Multitier Applications: Using JDBC from a Servlet • HTML files – <INPUT TYPE=CHECKBOX NAME=name VALUE=value> • Creates checkbox, any number can be selected – <INPUT TYPE=TEXT NAME=name> • Creates text field, user can input data

Multitier Applications: Using JDBC from a Servlet • Example servlet – Guest book to

Multitier Applications: Using JDBC from a Servlet • Example servlet – Guest book to register for mailing lists – HTML document first tier • Get data from user – Use servlet as middle tier • Provides access to database • Set up connection in init – Microsoft Access database (third tier)

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Fig. 19. 16: Guest. Book. Servlet. java // Three-Tier Example import java. io. *; import javax. servlet. http. *; import java. util. *; import java. sql. *; public class Guest. Book. Servlet extends Http. Servlet { private Statement statement = null; private Connection connection = null; private String URL = "jdbc: odbc: Guest. Book"; 1. import 1. 1 URL 2. init 2. 1 Connect to database public void init( Servlet. Config config ) throws Servlet. Exception { init called exactly once, before super. init( config ); client requests are processed. Note the first line format. try { Class. for. Name( "sun. jdbc. odbc. Jdbc. Odbc. Driver" ); connection = Driver. Manager. get. Connection( URL, "" ); } catch ( Exception e ) { e. print. Stack. Trace(); Get connection to database (no name/password). connection = null; } }

30 31 32 33 34 35 36 37 38 39 40 41 42 43

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public void do. Post( Http. Servlet. Request req, Http. Servlet. Response res ) throws Servlet. Exception, IOException { String email, first. Name, last. Name, company, snailmail. List, cpp. List, java. List, vb. List, iwww. List; email = req. get. Parameter( "Email" ); first. Name = req. get. Parameter( "First. Name" ); last. Name = req. get. Parameter( "Last. Name" ); company = req. get. Parameter( "Company" ); snailmail. List = req. get. Parameter( "mail" ); cpp. List = req. get. Parameter( "c_cpp" ); java. List = req. get. Parameter( "java" ); vb. List = req. get. Parameter( "vb" ); iwww. List = req. get. Parameter( "iwww" ); Print. Writer output = res. get. Writer(); res. set. Content. Type( "text/html" ); if ( email. equals( "" ) || first. Name. equals( "" ) || last. Name. equals( "" ) ) { output. println( "<H 3> Please click the back " + "button and fill in all " + "fields. </H 3>" ); output. close(); return; } 3. do. Post 3. 1 get. Parameter 3. 2 get. Writer 3. 3 println

60 61 62 63 64 65 /* Note: The Guest. Book database actually contains

60 61 62 63 64 65 /* Note: The Guest. Book database actually contains fields * Address 1, Address 2, City, State and Zip that are not * used in this example. However, the insert into the * database must still account for these fields. */ boolean success = insert. Into. DB( 66 "'" + email + "', '" + first. Name + "', '" + last. Name + 67 "', '" + company + "', ' ', '" + 68 ( snailmail. List != null ? "yes" : "no" ) + "', '" + 69 ( cpp. List != null ? "yes" : "no" ) + "', '" + 70 ( java. List != null ? "yes" : "no" ) + "', '" + 71 ( vb. List != null ? "yes" : "no" ) + "', '" + 72 73 74 75 76 ( iwww. List != null ? "yes" : "no" ) + "'" ); if ( success ) output. print( "<H 2>Thank you " + first. Name + " for registering. </H 2>" ); 77 else 78 output. print( "<H 2>An error occurred. " + 79 "Please try again later. </H 2>" ); 80 81 82 83 84 85 output. close(); } private boolean insert. Into. DB( String stringtoinsert ) { 86 try { 87 statement = connection. create. Statement(); 4. insert. Into. DB 4. 1 create. Statement

88 statement. execute( 89 "INSERT INTO Guest. Book values (" + 90 stringtoinsert +

88 statement. execute( 89 "INSERT INTO Guest. Book values (" + 90 stringtoinsert + "); " ); Insert data into database. 91 statement. close(); 92 } 93 catch ( Exception e ) { 94 System. err. println( 95 "ERROR: Problems with adding new entry" ); 96 e. print. Stack. Trace(); 97 return false; 98 } 99 100 return true; 101 } destroy called automatically, 102 103 public void destroy() closes connection to database. 104 { 105 try { 106 connection. close(); 107 } 108 catch( Exception e ) { 109 System. err. println( "Problem closing the database" ); 110 } 111 } 112 } 4. 2 INSERT INTO 5. destroy 5. 1 close

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <!-- Fig. 19. 17: Guest. Book. Form. html --> <HTML> <HEAD> <TITLE>Deitel Guest Book Form</TITLE> </HEAD> HTML file <BODY> <H 1>Guest Book</H 1> <FORM ACTION=http: //lab. cs. siu. edu: 8080/rahimi/Guest. Book. Servlet METHOD=POST><PRE> * Email address: <INPUT TYPE=text NAME=Email> * First Name: <INPUT TYPE=text NAME=First. Name> * Last name: <INPUT TYPE=text NAME=Last. Name> Company: <INPUT TYPE=text NAME=Company> * fields are required </PRE> <P>Select mailing lists from which you want to receive information<BR> <INPUT TYPE=CHECKBOX NAME=mail VALUE=mail> Snail Mail<BR> <INPUT TYPE=CHECKBOX NAME=c_cpp VALUE=c_cpp> <I>C++ How to Program & C How to Program</I><BR> <INPUT TYPE=CHECKBOX NAME=java VALUE=java> <I>Java How to Program</I><BR> <INPUT TYPE=CHECKBOX NAME=vb VALUE=vb> <I>Visual Basic How to Program</I><BR> 1. <FORM> 1. 1 TYPE=text 2. TYPE=CHECKBOX Create text fields and checkboxes for user input.

30 31 <INPUT TYPE=CHECKBOX NAME=iwww VALUE=iwww> 32 <I>Internet and World Wide Web How to

30 31 <INPUT TYPE=CHECKBOX NAME=iwww VALUE=iwww> 32 <I>Internet and World Wide Web How to Program</I><BR> 33 </P> 34 <INPUT TYPE=SUBMIT Value="Submit"> 35 </FORM> 36 </BODY> 37 </HTML>

Program Output

Program Output

Program Output

Program Output

Electronic Commerce • Revolution in electronic commerce – – 2/3 of stock transactions by

Electronic Commerce • Revolution in electronic commerce – – 2/3 of stock transactions by 2007 amazon. com, ebay. com, huge volumes of sales Business to business transactions Servlet technology • Help companies get into e-commerce – Client-server systems • Many developers use all Java • Applets for client, servlets for server