Servlets DBI Representation and Management of Data on
Servlets DBI - Representation and Management of Data on the Web 1
What is a Servlet • Java technology for Common Gateway Interface (CGI) • Servlets are Java programs that serve as an intermediating layer between an HTTP request of a client and applications in the Web server 2
For Example • Programs that runs on the server: – Should sometimes access a database – Should sometimes access the file system – Should create of Web pages online 3
Using Servlets • Reading the data that the user sent (HTTP request) • Receiving information from the HTTP request • Running an application with respect to the given input • The application creates a document for the response (e. g. , HTML document) • Parameters are defined for the HTTP response • The created document is sent to the user 4
A Java Servlet Sending a request and receiving a response 5
Servlets • Servlets most common usages: – 1. Used to extend Web servers – 2. Used as replacement for CGI that is • secure, portable, and easy-to-use • A servlet is a dynamically loaded module that services requests from a Web server • A servlet runs entirely inside the Java Virtual Machine 6
Supporting Sevlets • The Web server must support servlets: – Apache Tomcat – Sun’s Java. Server Web Development Kit (JSWDK) – Allaire Jrun – an engeine that can be added to IIS, PWS, old Apache Web servers etc… – Sun’s Java Web Server –… 7
Tomcat A Web Server that Support Servlets and Java Server Pages (JSP( 8
Installing Tomcat • Choose the installation directory (tomcat_home) • > tomcat setup in the installation directory • You get the directories: – – – conf/ lib/ logs/ my-webapps-template-dir/ webapps/ 9
Working with Tomcat • In the installation directory: – Use the command tomcat start to start the server – Use the command tomcat stop to stop the server – You get to the server by requesting on a web browser http: //<host>: port/ • Host is the machine on which you started tomcat • Port is the port number according to the configuration 10
11
Definitions and Configuration • Definition files are in the directory tomcat_home/conf/ • The definition of the port number of the server is in the file tomcat_home/conf/server. xml 12
Changing the Port server. xml <!-- Normal HTTP --> >Connector class. Name= "org. apache. tomcat. service. Pool. Tcp. Connector<" <Parameter name="handler" value="org. apache. tomcat. service. http. Http. Connection. Handler</" <Parameter name="port" value="8080"/> />Connector< 13
MIME-Types Mappings tomcat_home/conf/web. xml <mime-mapping> <extension>txt</extension> <mime-type>text/plain</mime-type> </mime-mapping> <extension>html</extension> >mime-type>text/html</mime-type< />mime-mapping< … 14
Servlets Class Files • Place for the servlet files: – tomcat_home/webapps/ROOT/WEBINF/classes • Standard place for servlet classes – tomcat_home/user_dir/WEB-INF/classes • User defined position for servlet classes – tomcat_home/lib • Position for JAR files with classes 15
User Defined Directories • The definition is in the file server. xml inside the tag <Context. Manager … >, <Context path="/dbi" doc. Base="webapps/dbi" cross. Context=“true" debug="0" reloadable="true" > </Context> 16
Mapping Directories <Context path="/dbi" doc. Base="webapps/dbi" … < </Context> http: //host: 8080/dbi/servlet/My. Servlet tomcat_home/webapps/dbi/ WEB-INF/classes/My. Servlet. class 17
Important Note • Do not forget to stop tomcat before you logout from your account • Otherwise, tomcat will continue running and will not allow others to use the socket defined for it 18
Working with Servlets 19
Servlet Package • javax. servlet • The Servlet interface defines methods that manage servlets and their communication with clients • Client Interaction: when it accepts call, receives two objects that implements – Servlet. Request – Servlet. Response 20
Architecture Servlet Generic Servlet Http. Servlet Your. Own. Servlet 21
Creating a Servlet Extend HTTPServlet Implement do. Get Implement do. Post The methods should get an input (the HTTP request) Should create an output (the HTTP response) 22
Creating a Servlet. Request HTTPServlet. Request Implement do. Get Implement do. Post Servlet. Response HTTPServlet. Response 23
import java. io. *; import javax. servlet. http. *; Hello World Example 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 ("<!DOCTYPE HTML PUBLIC ”-//W 3 C//DTD HTML 4. 0 Transitional//EN”>"); out. println("<HTML><HEAD><TITLE>Hello World</TITLE></HEAD>"); out. println(“<BODY><BIG>Hello World </BIG></BODY></HTML>"); out. close(); } } 24
import java. io. *; import javax. servlet. http. *; Hello World Example 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 ("<!DOCTYPE HTML PUBLIC ”-//W 3 C//DTD HTML 4. 0 Transitional//EN”>"); out. println("<HTML><HEAD><TITLE>Hello World</TITLE></HEAD>"); out. println(“<BODY><BIG>Hello World </BIG></BODY></HTML>"); out. close(); } } 25
26
Compiling • In order to compile a servlet, you may need to add to your CLATHPATH definition the following: setenv CLASSPATH }$CLASSPATH: { /usr/local/java/apache/jakarta-tomcat/lib/ant. jar: /usr/local/java/apache/jakarta-tomcat/lib/jasper. jar: /usr/local/java/apache/jakarta-tomcat/lib/jaxp. jar: /usr/local/java/apache/jakarta-tomcat/lib/parser. jar: /usr/local/java/apache/jakarta-tomcat/lib/servlet. jar: /usr/local/java/apache/jakarta-tomcat/ lib/webserver. jar 27
Calling the Servlet • Calling the servlet is done from the Web browser: http: //host: port/servlet/Servlet. Name For servlets that are positioned under webapps/ROOT/WEB-INF/classes 28
Calling the Servlet • Calling the servlet is done from the Web browser: http: //host: port/dir. Name/servlet/Servlet. Name For servlets that are positioned under dir_path/WEB-INF/classes and dir_path is mapped to dir. Name 29
Packages • Add packege package. Name to the java code to create a package • Put the classes files under tomcat_home/webapps/ROOT/WEBINF/classes/package. Name • Call the servlet with http: //host: port/servlet/package. N ame. servlet. Name 30
Servlet Life Cycle • • • No main() method! The server loads and initializes the servlet The servlet handles client requests The server can remove the servlet The servlet can remain loaded to handle additional requests • Incur startup costs only once 31
Life Cycle Schema 32
Servlet Life Cycle Calling the init method Servicing requests by calling the service method Servlet. Config Initialization and Loading Servlet Class Destroying the servlet by calling the destroy method Garbage Collection 33
Important Note • When you change the servlet, usually it is not enough just to compile it – why? • What should you do? • You need to stop tomcat and restart tomcat to make tomcat reload the servlet and not use the old version stored in memory 34
Starting Servlets • Initialization: – Servlet’s init(Servlet. Config) or init() methods – Called when the servlet is called for the first time from a client – A code for initialization that is called only once (e. g. , creating the tables of the database) – Initialization parameters are server specific 35
The Configuration Parameters • The configuration parameters are taken from the file web. xml that is under tomcat_home/dir_path/WEB-INF/ 36
<? 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>Init. Example</servlet-name> <servlet-class>Servlet. Init</servlet-class> <init-param> <param-name>dbi</param-name> <param-value>http: //www. cs. huji. ac. il/~dbi</param-value> </init-param> <param-name>db</param-name> <param-value>http: //www. cs. huji. ac. il/~db</param-value> </init-param> </servlet> </web-app> 37
import java. io. *; import javax. servlet. http. *; /** *Example using servlet initialization. */ public class Servlet. Init extends Http. Servlet { String dbi. Url, db. Url; public void init(Servlet. Config config) throws Servlet. Exception { // Always call super. init(config); dbi. Url = config. get. Init. Parameter("dbi"); db. Url = config. get. Init. Parameter("db"); } 38
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 = response. get. Writer(); String title = "Initialization Example 2"; out. println ("<!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN">"); out. println("<HTML><HEAD>"); out. println("<TITLE>"+title+"</TITLE></HEAD>"); out. println("<BODY><H 1>Links to courses</H 1>"); out. println("<TABLE><TR><TH>Course”); out. println(“</TH><TH>Link</TH></TR>"); out. println("<TR><TD>dbi</TD><TD>"+dbi. Url+"</TD></TR>"); out. println("<TR><TD>db</TD><TD>"+db. Url+"</TD></TR>"); out. println("</TABLE></BODY></HTML>"); } } 39
http: //pita. cs. huji. ac. il: 8080/dbi/servlet/Init. Example 40
HTTP Methods • POST: – Data sent in two steps – Designed for Posting information • Browser contacts server • Sends data • GET: – Contacts server and sends data in single step – Appends data to action URL separated by question mark – Designed to get information 41
Other Methods • HEAD: Client sees only header of response • • to determine size, etc… PUT: Place documents directly on server DELETE: Opposite of PUT TRACE: Debugging aid returns to client contents of its request OPTIONS: what options available on server 42
Servicing a Servlet • Every call to the servlet creates a new thread that calls the service method • The service methods check the type of request (GET, POST, PUT, DELETE, TRACE, OPTION) and call the appropriate method: do. Get, do. Post, do. Put, do. Delete, Do. Trace, do. Option • It is recommended to implement do. Post and do. Get instead of implementing service. Why? • The method do. Post can call do. Get in order to reuse code 43
More on Service • There is an automatic support for TRACE and OPTIONS by do. Get so you do not have to implement them • There is no method do. Head. Why? 44
Http. Servlet Request Handling Web GET request Server Http. Servlet subclass do. Get() response service() POST request do. Post() response 45
The Single Thread Model • Usually there is a single instance of a servlet and a thread for each user request • The do. Get and do. Post methods must synchronize the access to data structures and other resources • If it is required to prevent a concurrent access to an instance of a servlet you should use the single thread model 46
Single. Thread. Model • Single. Thread. Model is a marker interface – No methods – Tells servlet engines about lifecycle expectations • Ensure that no two threads will execute concurrently the service method of that servlet • This is guaranteed by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet 47
Single. Thread. Model • Single. Thread. Model let you break servlet functionality into multiple methods • Can rely on “instance state” being uncorrupted by other requests • Can’t rely on singletons (static members) or persistent instance state between connections – The same client making the same request, can get different instances of your servlet 48
Using the Single Thread Model public class yourservlet extends Http. Servlet implements Single. Thread. Model { …} • There are two options: – Requests are accessed one after the other to a single instance of the thread – An instance of the servlet is created for each request and there is a single instance per request • Does this prevents the need to synchronize access to all resources? 49
Destroying Servlets • Destroying: – destroy() method – make sure all service threads complete 50
Example – Counting Threads public Shutdown. Example extends Http. Servlet { private int service. Counter = 0; . . . //Access methods for service. Counter protected synchronized void entering. Service. Method() { service. Counter++; } protected synchronized void leaving. Service. Method() { service. Counter--; } protected synchronized int num. Services() { return service. Counter; } } 51
Maintaining the Count protected void service(Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException { entering. Service. Method(); try { super. service(req, resp); } finally { leaving. Service. Method(); } } 52
Notifying a Shutdown public Shutdown. Example extends Http. Servlet { private boolean shutting. Down; . . . //Access methods for shutting. Down protected set. Shutting. Down(boolean flag) { shutting. Down = flag; } protected boolean is. Shutting. Down() { return shutting. Down; } } 53
A Destroy Example public void destroy() { /* Check to see whethere are still * service methods running, * and if there are, tell them to stop. */ if (num. Services() > 0) { set. Shutting. Down(true); } } /* Wait for the service methods to stop. */ while(num. Services() > 0) { try { Thread. sleep(interval); } catch (Interrupted. Exception e) {} } 54
“Listening” to a Shutdown public void do. Post(. . . ) {. . . for(i = 0; ((i < number. Of. Things. To. Do) && !is. Shutting. Down()); i++) { try { part. Of. Long. Running. Operation(i); } catch (Interrupted. Exception e) {} } } 55
Getting Input From the User HTML Forms 56
Handling a User Request • The servlet gets parameters from HTML forms • <form action=… method=…> …</form> comprise a single form – action – the name of the processing server – method – the HTTP method to use when passing parameters to the server – enctype – the encription used to send the parameters 57
The <input> Tag • Inside a form, INPUT tags define fields for data entry • Standard input types include: buttons, checkboxes, password field, radio buttons, text fields, imagebuttons, text areas, hidden fields, etc. • They all associate a single (string) value with a named parameter 58
Example <HTML> … <form method=“GET” action=“http: //pita. cs. huji. ac. il: 8090/servlet/update”> … <INPUT name=“x” type=“text”> <INPUT name=“y” type=“text”> <INPUT type=“submit”> <INPUT type=“reset”> </form> … </HTML> http: //pita. cs. huji. ac. il: 8090/servlet/update? x=19&y=104 59
Getting the Parameters Values request. get. Parameter(“x”); request. get. Parameter(“y”); If there can be multiple values for the parameter, use get. Parameter. Values If you don’t know the names of the parameters, use get. Parameter. Names 60
<!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <HTML> <HEAD> <TITLE>Sending Parameters</TITLE> </HEAD> <BODY BGCOLOR="#CC 90 E 0"> <H 1 ALIGN="LEFT">Please enter the parameters</H 1> <FORM ACTION=“dbi/servlet/Set. Colors” METHOD=“GET”> <TABLE> <TR><TD>Background color: </TD> <TD><INPUT TYPE="TEXT" NAME="bgcolor"></TD></TR> <TR><TD>Font color: </TD> <TD><INPUT TYPE="TEXT" NAME="fgcolor"></TD></TR> <TR><TD>Font size: </TD> <TD><INPUT TYPE="TEXT" NAME="size"></TD></TR> </TABLE> <BR> <INPUT TYPE="SUBMIT" VALUE="Show Page"> </FORM> </BODY> </HTML> tomcat_home/webapps/ROOT/colors. html 61
http: //pita. cs. huji. ac. il: 8080/colors. html 62
http: //pita. cs. huji. ac. il: 8080/dbi/servlet/ Set. Colors? bgcolor=wheat&fgcolor=blue&size=5 63
import java. io. *; import javax. servlet. http. *; /** * Creates a page according to the parameters * given from a form */ public class Set. Colors extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { String title = "Set Colors Example"; response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String bg = request. get. Parameter("bgcolor"); String fg = request. get. Parameter("fgcolor"); String size = request. get. Parameter("size"); 64
out. println("<HTML><HEAD><TITLE>" + title + "</TITLE></HEAD>"); out. println("<BODY text='" + fg + "' bgcolor='" + bg + "'>"); out. println("<H 1>" + title + "</H 1>"); out. println("<FONT size='" + size + "'>"); out. println("You requested a background color " + bg + "<P>"); out. println("You requested a font color " + fg + "<P>"); out. println("You requested a font size " + size + "<P>"); out. println("</FONT></BODY></HTML>"); } } 65
Handling Post <FORM ACTION=“dbi/servlet/Set. Colors” METHOD=“POST”> public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(request, response); } 66
Information on Client Request request. get. Header(“Accept”); request. get. Header. Names(); get. Cookies get. Content. Length get. Content. Type get. Method get. Protocol … 67
import java. io. *; javax. servlet. http. *; java. util. *; /** * Shows the request headers sent on the request */ public class Show. Request. Headers extends Http. Servlet { 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 = response. get. Writer(); String title = "Servlet Example: Showing Request Headers"; 68
out. println("<HTML><HEAD><TITLE>" + title + "</TITLE></HEAD>" + "<BODY BGCOLOR="#AACCAA" TEXT="#990000">n" + "<H 1 ALIGN=CENTER>" + title + "</H 1>n" + "<B>Request Method: </B>" + request. get. Method() + "<BR>n" + "<B>Request URI: </B>" + request. get. Request. URI() + "<BR>n" + "<B>Request Protocol: </B>" + request. get. Protocol() + "<BR>n" + "<TABLE BORDER=1 ALIGN=CENTER>n" + "<TR BGCOLOR="#88 AA 88">n" + "<TH>Header Name<TH>Header Value"); Enumeration header. Names = request. get. Header. Names(); while(header. Names. has. More. Elements()) { String header. Name = (String)header. Names. next. Element(); out. println("<TR><TD>" + header. Name); out. println("<TD>“ + request. get. Header(header. Name)); } out. println("</TABLE>n</BODY></HTML>"); } 69
/** Let the same servlet handle both GET and POST. */ public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(request, response); } } 70
71
72
Creating the Response of the Servlet 73
HTTP Response • The response includes: – Status line: version, status code, status message – Response headers – Empty line – Document HTTP/1. 1 200 OK Content-Type: text/plain Bla Bla 74
Buffer Servlet Buffer server response set. Buffer. Size get. Buffer. Size is. Comitted flush. Buffer reset request client 75
Setting the Response Status • The status code of the HTTP response can be set by the set. Status method of HTTPServlet. Response • The status should be defined before sending content through the Print. Writer of the HTTPServlet. Response • The status can be defined after setting headers of the HTTPServlet. Response 76
Shortcuts • An automatic response is created by – send. Error(int code, String message) • Returns the status code with the message • Usually status code 404 (HTTPServlet. Response. SC_NOT_FOUND) – send. Redirect(String url) • Creates a response with status code 302 (HTTPServlet. Response. SC_MOVED_TEMPORARILY) with a Location header that includes the given url 77
Using Redirect • You can create a servlet that – Gets a url from a user (e. g. , from a form) – Return a redirect message with the given url • Or – Get a list of words from the user – Return a redirect message to a search engine with the given words as parameters 78
Setting Response Headers • Headers can be defined – using set. Header(String header, String value) of HTTPServlet. Response – using set. Int. Header(String header, int value) – using set. Date. Header(String header, long milliseconds) (translate to GMT) • The headers must be defined before the first time the buffer content is sent 79
More Headers Methods • You can use – contains. Header to check existence of an header in the response – set. Content. Type – set. Content. Length – add. Cookie 80
Servlet Description • To allow server to display information about servlet you should implement get. Servlet. Info public class My. Servlet extends Http. Servlet {. . . public String get. Servlet. Info() { return new String(“The invisible servletn“ + “Author: Danny Dinn” + “Description: A servlet to show things that cannot be seen”; } } 81
End of Servlets Basics 82
- Slides: 82