Java Servlets Part I Server and Servlet Basics

Java Servlets Part I Server and Servlet Basics Part II Session Tracking and Servlet Collaboration Web Technologies 1

Part I : Server and Servlet Basics • • Network. Server. java and Echo. Server. java Post. Form. html Get. Form. html More HTML form examples Web Technologies 2

Network. Server. java // Network. Server. java Adapted from "Core Servlets // and Java Server Pages" // by Marty Hall No Tomcat server. import java. net. *; Just this code. import java. io. *; public class Network. Server { private int port; private int max. Connections; Web Technologies 3

protected void set. Port(int port) { this. port = port; } public int get. Port() { return port; } protected void set. Max. Connections(int max) { max. Connections = max; } public int get. Max. Connections() { return max. Connections; } public Network. Server(int port, int max. Connections) { set. Port(port); set. Max. Connections(max. Connections); } Web Technologies 4

// Wait for a connections until max. Connections. // On each connection call handle. Connection() passing // the socket. If max. Connections == 0 loop forever public void listen() { int i = 0; try { Server. Socket listener = new Server. Socket(port); Socket server ; while((i++ < max. Connections) || (max. Connections == 0)) { server = listener. accept(); // wait for connection handle. Connection(server); } } catch (IOException ioe) { System. out. println("IOException : " + ioe); ioe. print. Stack. Trace(); } Web Technologies 5 }

// Open readers and writers to socket. // Display client's host name to console. // Read a line from the client and display it on the console. // Send "Generic network server" to the client. // Override this method. protected void handle. Connection(Socket server) throws IOException { Buffered. Reader in = new Buffered. Reader( Input. Stream for reading bytes new Input. Stream. Reader( server. get. Input. Stream() )); Flush buffer on println Print. Writer out = new Print. Writer( server. get. Output. Stream(), true); Web Technologies Readers and Writers 6 to work with characters

System. out. println("Generic network server: got connection from "+ server. get. Inet. Address(). get. Host. Name() + "n" + "with first line '" + in. read. Line() + "'"); out. println("Generic network server"); To server’s server. close(); console. } To client. public static void main(String args[]) { Network. Server test = new Network. Server(6502, 5); test. listen(); } } Web Technologies 7

Compile, Run and Visit Client Server C: Mc. Carthywww46 -928examplesnetworking>java Network. Server Generic network server: got connection from localhost with first line 'GET / HTTP/1. 0' Web Technologies 8

Echo. Server. java /* From Core Servlets, Marty Hall An HTTP Request header example Notes GET /path/file. html HTTP/1. 0 Accept: text/html Accept: audio/x User-agent: Mac. Web Request terminated by two returns HTTP defines dozens of possible headers. Web Technologies The whitespace is required. Accept header fields tell the server MIME types (Multipurpose Internet Mail Extension) that are handled by the browser. Still no Tomcat 9

Echo. Server. java An HTTP Response header example HTTP 1. 0 200 OK Server: NCSA/1. 4. 2 MIME-version: 1. 0 Content-type: text/html Content-length: 107 <html> : : </html> Response code MIME type Blank line The client must interpret this MIME encoded data. Web Technologies 10
![HTTP General form <method> <resource identifier> <HTTP Version> <crlf> [<Header> : <value>] <crlf> : HTTP General form <method> <resource identifier> <HTTP Version> <crlf> [<Header> : <value>] <crlf> :](http://slidetodoc.com/presentation_image_h2/c20b4bbf62b76f45d64da4328d15348c/image-11.jpg)
HTTP General form <method> <resource identifier> <HTTP Version> <crlf> [<Header> : <value>] <crlf> : : : [<Header> : <value>] <crlf> a blank line [entity body] The resource identifier field specifies the name of the target resource; it's the URL stripped of the protocol and the server domain name. When using the GET method, this field will also contain a series of name=value pairs separated by ‘&’. When using a POST method, the entity body contains these pairs. The HTTP version identifies. Web the. Technologies protocol used by the client. */ 11

// Adapted from Core Servlets and Java. Server. Pages // by Marty Hall, chapter 16 import java. net. *; import java. io. *; import java. util. String. Tokenizer; public class Echo. Server extends Network. Server { protected int max. Request. Lines = 50; // Post data is brought in // as a single string. protected String server. Name = "Echo. Server"; public static void main(String a[]) { int port = 6502; new Echo. Server(port, 0); } // loop forever Web Technologies 12

public Echo. Server(int port, int max. Connections) { super(port, max. Connections); // call base class constructor listen(); // call base class listen() } // listen calls handle. Connection() // Overrides base class handle. Conection and is called by listen() public void handle. Connection(Socket server) throws IOException { // Assign readers and writers to the socket Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( server. get. Input. Stream() )); Print. Writer out = new Print. Writer(server. get. Output. Stream(), true) // Announce connection to console System. out. println(server. Name + " got connection from "+ server. get. Inet. Address(). get. Host. Name() + "n"); Web Technologies 13
![String input. Lines[] = new String[max. Request. Lines]; int i; for(i = 0; i String input. Lines[] = new String[max. Request. Lines]; int i; for(i = 0; i](http://slidetodoc.com/presentation_image_h2/c20b4bbf62b76f45d64da4328d15348c/image-14.jpg)
String input. Lines[] = new String[max. Request. Lines]; int i; for(i = 0; i < max. Request. Lines; i++) { input. Lines[i] = in. read. Line(); if(input. Lines[i] == null) break; // client closed connection if(input. Lines[i]. length() == 0) { // blank line // maybe done or maybe post if(using. Post(input. Lines)) { // read. Post. Data reads into a single string // at location i+1 read. Post. Data(input. Lines, i, in); // i was not changed in the procedure so // bump it one past the post data string i = i + 2; } break; // we’re done either way } Web Technologies 14 }
![print. Header(out); for(int j = 0; j < i; j++) { out. println(input. Lines[j]); print. Header(out); for(int j = 0; j < i; j++) { out. println(input. Lines[j]);](http://slidetodoc.com/presentation_image_h2/c20b4bbf62b76f45d64da4328d15348c/image-15.jpg)
print. Header(out); for(int j = 0; j < i; j++) { out. println(input. Lines[j]); } // HTTP + HTML print. Trailer(out); server. close(); // Closing HTML //Request Data } Web Technologies 15

HTTP Response private void print. Header(Print. Writer out) { headers plus HTML. out. println( "HTTP/1. 0 200 OKrn" + "Server: " + server. Name + "rn" + "Content-Type: text/htmlrn" + “rn” + "<!DOCTYPE HTML PUBLIC " + ""-//W 3 C//DTD HTML 4. 0 Transitional//EN">n" + "<HTML>n" + "<HEAD>n" + " <TITLE>" + server. Name + " Results</TITLE>n" + "</HEAD>n" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<H 1 ALIGN="CENTER">" + server. Name + " Results</H 1>n" + "Here is your request line and request headersn" + "sent by your browser: n" + "<PRE>“ ); // honors whitespace Web Technologies 16 }

private void print. Trailer(Print. Writer out) { // Close HTML out. println("</PRE>n" + "</BODY>n" + "</HTML>n"); } // Checks if post private boolean using. Post(String[] inputs) { return (inputs[0]. to. Upper. Case(). starts. With("POST")); } Web Technologies 17

// Read the post data as a single array of char and place it all // in one string. private void read. Post. Data (String inputs[], int i, Buffered. Reader in) throws IOException { int content. Length = content. Length(inputs); char post. Data[] = new char[content. Length]; in. read(post. Data, 0, content. Length); // All of the post data is converted to a single string inputs[++i] = new String(post. Data, 0, content. Length); } Web Technologies 18

// The header fields may arrive in any order. // Search for and return the CONTENT-LENGTH. private int content. Length(String inputs[]) { String input; for(int i = 0; i < inputs. length; i++) { if(inputs[i]. length() == 0) break; input = inputs[i]. to. Upper. Case(); if(input. starts. With("CONTENT-LENGTH")) return (get. Length } return (0); } // Return the integer associated with the second token. private int get. Length(String length) { String. Tokenizer tok = new String. Tokenizer(length); tok. next. Token(); return (Integer. parse. Int(tok. next. Token())); } Web Technologies 19 }

Post. Form. html <!-- Post. Form. html --> <html> <head> <title>Post Form</title> Visit the port </head> <body> <form method="post" action="http: //localhost: 6502"> Hi, what is your name? <input type="text" name = "name"> <p> What is your age? <input type="text" name = "age"> <p> <input type = "submit"> </form> </body> Web Technologies </html> 20

Post. Form. html Browser Web Technologies 21

Echo. Server Response Using POST Size of POST data Name value pairs with spaces as ‘+’ etc. Web Technologies 22

Get. Form. html <!-- Get. Form. html --> <html> <head> <title>Get Form</title> </head> <body> <form method="get" action="http: //localhost: 6502"> Hi, what is your name? <input type="text" name = "name"> <p> What is your age? <input type="text" name = "age"> <p> <input type = "submit"> </form> </body> Web Technologies </html> 23

Get. Form. html Browser Web Technologies 24

Echo. Server Response Using GET data Web Technologies 25

A Form With Checkboxes <!-- Check. Box. html --> <html> <head> <title>Check. Boxes</title> </head> <body BGCOLOR="WHITE"> <form action="http: //localhost: 6502"> <dl> <dt> Select Pizza Toppings </dt> <dd><Input type = "Check. Box" name = "Pepperoni"> Pepperoni <dd><Input type = "Check. Box" name = "Sausage"> Sausage <dd><Input type = "Check. Box" name = "Extra Cheese"> Extra Cheese <dd><Input type = "Check. Box" name = "Mushrooms"> Mushrooms <p> <input type = "submit"> </dl> </form> Web Technologies 26 </body>

Check. Boxes Browser Web Technologies 27

Check. Box Response Data from client Web Technologies 28

Radio. Boxes HTML <!-- Radio. html --> <html> <head> <title>Radio Buttons</title> </head> <body BGCOLOR="WHITE"> <form action="http: //localhost: 6502"> <dl> <dt> Please Vote </dt> <!– Definition list --> <!- The term to be defined left margin--> <!-- Item definitions indented and below --> <dd><Input type = "Radio" name = "president" value= "Bush"> <b>George W. Bush</b> <dd><Input type = "Radio" name = "president" value = "Gore"> Al Gore <dd><Input type = "Radio" name = "president" value = "Buchanan"> Pat Buchanan <dd><Input type = "Radio" name = "president" value = "Nader"> Ralph Nader <p> <input type = "submit"> </dl> </form> </body> Web Technologies 29 </html>

Radio. Boxes Browser Web Technologies 30

Echo. Server Response Web Technologies 31

Reading Form Data With Servlets Under Tomcat // Query. Data. java -- Handle the voting form in radio. html import java. io. *; import javax. servlet. http. *; We have less work to do. public class Query. Data extends Http. Servlet { public void do. Post(Http. Servlet. Request req, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(req, response); Web Technologies } 32

public void do. Get(Http. Servlet. Request req, Http. Servlet. Response response) throws Servlet. Exception, IOException { String new. President = req. get. Parameter("president"); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String doc. Type = "<!DOCTYPE HTML PUBLIC "//W 3 C//DTD” + “HTML 4. 0 "; doc. Type += "Transitional//EN">n"; Web Technologies 33

out. println(doc. Type + "<HTML>n" + "<HEAD><TITLE>Presidential Servlet" + "</TITLE>” + “</HEAD>n" + "<BODY>n" + "<H 1>The new president is "+ new. President + "</H 1>n" + "</BODY></HTML>"); } } Web Technologies 34

<!-- Radio. html (Modified for servlets)--> <html> <head> Tomcat’s port <title>Radio Buttons</title> servlet </head> <body BGCOLOR="WHITE"> <form action="http: //localhost: 8080/Cool. Servlet/Query. Data"> <dl> <dt> Please Vote </dt> <dd><Input type = "Radio" name = "president" value= "Bush"> <b>George W. Bush</b> <dd><Input type = "Radio" name = "president" value = "Gore"> Al Gore <dd><Input type = "Radio" name = "president" value = "Buchanan"> Pat Buchan <dd><Input type = "Radio" name = "president" value = "Nader"> Ralph Nader <p> <input type = "submit"> </dl> </form> </body> </html> Web Technologies 35

Radio HTML in the browser Web Technologies 36

The Servlet’s Response Web Technologies 37
![Organizing The Files C: | ---president | build. properties build. xml [src] [web] Query. Organizing The Files C: | ---president | build. properties build. xml [src] [web] Query.](http://slidetodoc.com/presentation_image_h2/c20b4bbf62b76f45d64da4328d15348c/image-38.jpg)
Organizing The Files C: | ---president | build. properties build. xml [src] [web] Query. Data. java [WEB-INF] Radio. html web. xml Web Technologies 38

build. properties # Context path to install this application on app. path=/Cool. Servlet # Tomcat 4 installation directory catalina. home=d: /jwsdp-1_0_01 # Manager webapp username and password manager. username=xxxxxxx manager. password=xxxxxxx Web Technologies 39

web. xml <? xml version="1. 0" encoding="ISO-8859 -1"? > <!-Copyright 2002 Sun Microsystems, Inc. All rights reserved. SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. --> <!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>Query. Data. Id</servlet-name> <servlet-class>Query. Data</servlet-class> <load-on-startup/> </servlet> <servlet-mapping> <servlet-name>Query. Data. Id</servlet-name> <url-pattern>/Query. Data/*</url-pattern> Web Technologies </servlet-mapping> </web-app> 40

Running Ant on build. xml Produces a build directory with the following structure: build │ Radio. html │ └───WEB-INF │ │ web. xml │ ├───classes │ Query. Data. class │ Web Technologies └───lib 41

Handling Check. Boxes <!-- Check. Box. html --> <html> <head> servlet <title>Check. Boxes</title> </head> <body BGCOLOR="WHITE"> <form action="http: //localhost: 8080/servlet/Pizza. Data"> <dl> <dt> Select Pizza Toppings </dt> <dd><Input type = "Check. Box" name = "Pepperoni"> Pepperoni <dd><Input type = "Check. Box" name = "Sausage"> Sausage <dd><Input type = "Check. Box" name = "Extra Cheese"> Extra Cheese <dd><Input type = "Check. Box" name = "Mushrooms"> Mushrooms <p> <input type = "submit"> </dl> </form> Web Technologies 42 </body>

Pizza Toppings Web Technologies 43

Servlet Response Web Technologies 44

Pizza. Data Servlet // Pizza. Data. java -- Handle the toppings selection from pizza. html import java. io. *; import java. util. *; import javax. servlet. http. *; public class Pizza. Data extends Http. Servlet { public void do. Post(Http. Servlet. Request req, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(req, response); } Web Technologies 45

public void do. Get(Http. Servlet. Request req, Http. Servlet. Response response) throws Servlet. Exception, Enumerate over the IOException input. { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String final. String = ""; Enumeration param. Names = req. get. Parameter. Names(); while(param. Names. has. More. Elements()) { String param. Name = (String) param. Names. next. Element(); final. String += param. Name + ": " ; final. String += req. get. Parameter(param. Name) + "<p>"; } Web Technologies 46

String doc. Type = "<!DOCTYPE HTML PUBLIC "//W 3 C//DTD” + “ HTML 4. 0 "; doc. Type += "Transitional//EN">n"; out. println(doc. Type + "<HTML>n" + "<HEAD><TITLE>Pizza Selections" + "</TITLE>” + “</HEAD>n" + "<BODY>n" + "<H 1>" + final. String + "</H 1>n" + "</BODY></HTML>"); } } Web Technologies 47

Part II Session Tracking and Servlet Collaboration • First we will use a shared object • Then we’ll use the new Session Tracking API Web Technologies 48

Session Tracking with Servlets HTTP is a stateless protocol. We must have each user introduce themselves in some way. We’ll look at traditional session tracking and then look at the Session Tracking API. Web Technologies 49

Traditional Session Tracking • User Authorization • Hidden Form fields • URL Rewriting • Persistent cookies We’ll look at the first and last. Web Technologies 50

User Authorization • The web server requests the user name and password. The information is available to any servlet that needs it. • The browser resends the name and password with each subsequent request. • Data about the user and the user’s state can be saved in a shared object. Web Technologies 51

Shared Objects • A convenient way to store data associated with a user. • There are likely to be many servlets running. • They can collaborate through a shared object. • Only one instance of the shared object should exist. • It has to be available (in the classpath) of the servlets that needs it. • It will be used by several threads and therefore should protect itself against simultaneous access. • We’ll look at a shared object and two servlets that use it. Web Technologies 52

Visit. Tracker. java // Servlet collaboration can be done through a shared object. // Any servlet has access to this object and it only has one // instance. // It maintains a hash table of names and dates. // Sections of code that must not be executed simultaneously // are called critical sections. Java provides the synchronized // keyword to protect these critical sections. For a synchronized // instance method, Java obtains an exclusive lock on the class // instance. import java. util. *; Web Technologies 53

public class Visit. Tracker { private Map name. Date. Pairs; private static Visit. Tracker instance = new Visit. Tracker(); private Visit. Tracker() { // private constructor name. Date. Pairs = new Hash. Map(); } public static Visit. Tracker get. Instance() { return instance; } synchronized public void add. Visit(String user. Name) { name. Date. Pairs. put(user. Name, new Date()); } Web Technologies 54

synchronized public Date last. Visit(String name) { Date d = (Date)name. Date. Pairs. get(name); return d; } } Web Technologies 55

User Authorization • Administered by the web server – Tomcat • Edit Tomcat’s deployment descriptor • From within the servlet use String name = req. get. Remote. User(); to access the user name. • We have to assign user names and passwords. tomcat-users. xml <tomcat-users> <user name="tomcat" password="tomcat" roles="tomcat" /> <user name="role 1" password="tomcat" roles="role 1" /> <user name="both" password="tomcat" roles="tomcat, role 1" /> <user name="mike" password="tomcat" roles="student" /> </tomcat-users> • The following will keep track of the date of the last visit. Web Technologies 56

// User. Authorization. Demo. java // This servlet reads from Tomcat and finds the name of the // authorized user. It then adds it to a hash table storing // the time of this visit. It makes use of Visit. Tracker. import java. io. *; import java. util. *; import javax. servlet. http. *; public class User. Authorization. Demo extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { Web Technologies 57

res. set. Content. Type("text/plain"); Print. Writer out = res. get. Writer(); String name = req. get. Remote. User(); // ask the server if(name == null) { System. out. println("The system administrator should protect" + " this page. "); } else { out. println("This user was authorized by the server: " + name); Visit. Tracker visit = Visit. Tracker. get. Instance(); Date last = visit. last. Visit(name); if(last == null) out. println("Welcome, you were never here before"); else out. println("Your last visit was on " + last); visit. add. Visit(name); } } } Web Technologies 58

Cookies • A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. • The server can take that bit of information and use it as a key to recover information about prior visits. This information may be in a database or a shared object. • Cookies are read from the request object by calling get. Cookies() on the request object. • Cookies are placed in the browser by calling add. Cookie() on the response object. Web Technologies 59

Using Cookies // Cookie. Demo. java // This servlet uses a cookie to determine when the // last visit by this browser occurred. It makes use of // the Visit. Tracker object. // Cookies normally expire as soon as the browser exits. // We want the cookie to last one year and so we use // set. Max. Age(seconds) on the cookie. import java. io. *; import java. util. *; import javax. servlet. http. *; Web Technologies 60

public class Cookie. Demo extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res throws Servlet. Exception, IOException { res. set. Content. Type("text/plain"); Print. Writer out = res. get. Writer(); Cookie[] c = req. get. Cookies(); // If this person has been here before then we should have // a cookiedemouser field assigned to a unique id. String id = null; Web Technologies 61

if (c!=null) { // we may have the cookie we are after for (int i=0; i<c. length; i++) { if (c[i]. get. Name(). equals("cookiedemouser")) { id = c[i]. get. Value(); } break; } } Web Technologies 62

if (id == null) { // They have not been here before and need a // cookie. We get a unique string (with respect // to this host)and make sure it is of the 'query string' form. // It uses the clock. Don’t turn the clock back! String uid = new java. rmi. server. UID(). to. String(); id = java. net. URLEncoder. encode(uid); Cookie oreo = new Cookie("cookiedemouser", id); oreo. set. Max. Age(60*60*24*365); res. add. Cookie(oreo); } Visit. Tracker visit = Visit. Tracker. get. Instance(); Date last = visit. last. Visit(id); if(last == null) out. println("Welcome, you were never here befor else out. println("Your last visit was on " + last); visit. add. Visit(id); } Web Technologies 63

The New Session Tracking API • Support may vary depending on the server. • Implemented with cookies or with URL rewriting if cookies fail (URL rewriting requires help from the servlet). • Every user of the site is associated with a javax. servlet. http. Http. Session object • The session object can hold any arbitrary set of Java objects. • Servlets collaborate by accessing the session object. • The following example abstracts away shared object concerns. • All valid sessions are grouped together in a Http. Session. Context object Web Technologies 64

The Session Tracking API // Session. Demo. java // The session object associated with this user/browser is available // to other servlets. import java. io. *; import javax. servlet. http. *; import java. util. *; public class Session. Demo extends Http. Servlet { Web Technologies 65

public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/plain"); Print. Writer out = res. get. Writer(); // Get the current session object. Create one if none exists. Http. Session session = req. get. Session(true); // Get the Date associated with this session Date d = (Date)session. get. Attribute("dateofvisit"); if(d == null) out. println("Your first time, welcome!"); else out. println("Your last visit was on " + d); session. set. Attribute("dateofvisit", Web Technologies new Date()); }} 66
- Slides: 66