Servlets Sun tutorial to servlets 1 Introduction 2
- Slides: 64
Servlets Sun tutorial to servlets 1
Introduction 2
What is a Servlet? • Servlets are Java programs that can be run dynamically from a Web Server • Servlets are a server-side technology • A Servlet is an intermediating layer between an HTTP request of a client and the Web server 3
A Java Servlet request Servlet response Web browser Web server 4
An Example • In the following example, the local server calls the Servlet Time. Servlet with an argument supplied by the user • This example, as well as all the examples in this lecture can be found at http: //inferno: 5000/ (accessible only from CS!) 5
Reload / Refresh Servlet Result • Trying to refresh the content created by a servlet will lead to fetching a new content from the server • This is not the case with static resources • Response headers of a static (as opposed to a servlet generated) resource contain - Etag, Last-Modified • While trying to refresh a resource - Cache-Contol: max-age=0 is sent and that means the server/proxies will try to revalidate the resource - Only in the static case the resource could be revalidated against some values the client holds - So in the static case the client sends the Etag value attached to the If-None-Match header, and the Last-Modified value is sent in If-Modified. Since Clear the cache, open and then reload /dbi/Time. html Open and reload /dbi/init Compare the headers sent and received. 6
What do Servlets do? • Read data sent by the user (e. g. , form data) • Look up other information about the request in the HTTP request (e. g. authentication data, cookies, etc. ) • Generate the result (may do this by talking to a database, file system, etc. ) • Format the result in a document (e. g. , make it into HTML) • Set the appropriate HTTP response parameters (e. g. cookies, content-type, etc. ) • Send the document to the user 7
Supporting Servlets • To run Servlets, the Web server must support them - Apache Tomcat • - - - Also functions as a module for other Apache servers Sun Java System Web Server and Java System Application Server IBM's Web. Sphere Application Server BEA’s Weblogic Application Server Macromedia’s Jrun – an engine that can be added to Microsoft’s IIS, In your final project Apache’s Web servers and more. . . you will install this server to create a Oracle Application Server powerful website … 8
Creating a Simple Servlet Read more about the Servlet Interface 9
The Servlet Interface • Java provides the interface Servlet • Specific Servlets implement this interface • Whenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet (HTTP) response My. Servlet service(request, response) (HTTP) request 10
HTTP Request Methods • POST - application data sent in the request body • GET - application data sent in the URL • HEAD - client sees only header of response • PUT - place documents directly on server • DELETE - opposite of PUT • TRACE - debugging aid • OPTIONS - list communication options 11
Servlet Hierarchy Called by the servlet container to allow the servlet to respond to any request method Servlet Generic Servlet service(Servlet. Request, Servlet. Response) A generic, protocol-independent class, implementing Servlet Http. Servlet do. Get(Http. Servlet. Request , Http. Servlet. Response) do. Post(Http. Servlet. Request Your. Own. Servlet Http. Servlet. Response) do. Put Called by the servlet container to do. Trace allow the servlet to respond to a … specific request method 12
Class Http. Servlet • Class Http. Servlet handles requests and responses of HTTP protocol • The service() method of Http. Servlet checks the request method and calls the appropriate Http. Servlet method: do. Get, do. Post, do. Put, do. Delete, do. Trace, do. Options or do. Head That is, a class that can be sub- • This class is abstract classed but non instantiated. This class’ methods however are not abstract… Read more about the Http. Servlet Class 13
Creating a Servlet • Extend the class HTTPServlet • Implement do. Get or do. Post (or both) • Both methods get: - Http. Servlet. Request: methods for getting form (query) data, HTTP request headers, etc. - Http. Servlet. Response: methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client • Many times, we implement do. Post by calling do. Get, or viceversa Check the result of an empty implementation http: //localhost/dbi/empty You could also run: Check. Request. Servlet <host> /dbi/empty <port> <OTHER-METHODS> 14
import java. io. *; import javax. servlet. http. *; Hello. World. java public class Text. Hello. World extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { Print. Writer out = res. get. Writer(); out. println("Hello World"); } public void do. Post(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { do. Get(req, res); } } 15
Returning HTML • By default, no content type is given with a As you can check using Live. Http. Headers plug-in response • In order to generate HTML - Tell the browser you are sending HTML, by setting the Content-Type header (response. set. Content. Type()) - Modify the printed text to create a legal HTML page • You should set all headers before writing the document content. Can you guess why? Download Live. Http. Headers Extension 16
public class Hello. World extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { Hello. World. java Content type wasn’t set, but the browser will understand… Print. Writer out = response. get. Writer(); out. println("<html><head><title>Hello World</title></head>n"); out. println("<body>"); out. println("<h 2>" + new java. util. Date() + "</h 2>n"); out. println("<h 1>Hello World</h 1>n</body></html>"); } } 17
Configuring the Server my. App/WEB-INF/web. xml <web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class>Hello. World</servlet-class> </servlet> http: //inferno: 5000/dbi/hello my. App/WEB-INF/classes/Hello. World. class <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping></web-app> 18
Getting Information From the Request 19
An HTTP Request Example GET /default. asp HTTP/1. 0 Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */* Accept-Language: en Connection: Keep-Alive Host: magni. grainger. uiuc. edu User-Agent: Mozilla/4. 04 [en] (Win. NT; I ; Nav) Cookie: SITESERVER=ID=8 dac 8 e 0455 f 4890 da 220 ada 8 b 76 f; ASPSESSIONIDGGQGGGAF=JLKHAEICGAHEPPMJKMLDEM Accept-Charset: iso-8859 -1, *, utf-8 20
Getting HTTP Data • Values of the HTTP request can be accessed through the Http. Servlet. Request object • Get the value of the header hdr using get. Header("hdr") of the request argument • Get all header names: get. Header. Names() • Methods for specific request information: get. Cookies, get. Content. Length, get. Content. Type, get. Method, get. Protocol, etc. Read more about the Http. Request Interface 21
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"; out. println( "<html><head><title>" + title + "</title></head><body>n" + "<h 1>" + title+ "</h 1>n" + "<h 2>Request Method: "+request. get. Method()+"</h 2>" + "<h 2>Request URI: "+request. get. Request. URI()+"</h 2>" + "<h 2>Servlet. Path: "+request. get. Servlet. Path()+"</h 2>" + "<h 2>Request Protocol: "+request. get. Protocol()+"</h 2>" + "<table border="1">n" + "<tr><th>Header Name</th><th>Header Value</th></tr>"); 22
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 + "</td>" +"<td>"+request. get. Header(header. Name)+"</td></tr>"); } out. println("</table>n</body></html>"); } public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(request, response); } Compare the results of the different browsers } } 23
User Input in HTML • Using HTML forms, we can pass parameters to Web applications • <form action=… method=…> …</form> comprises a single form • action: the address of the application to which the form data is sent • method: the HTTP method to use when passing parameters to the application (e. g. get or post) 24
The <input> Tag • Inside a form, INPUT tags define fields for data entry • Standard input types include: buttons, checkboxes, password fields, radio buttons, text fields, imagebuttons, text areas, hidden fields, etc. • They all associate a single (string) value with a named parameter 25
GET Example <form method="get" action="http: //www. google. com/search"> <p><input name="q" type="text" /> <input type="submit" /> <input type="reset" /> </p> </form> http: //www. google. com/search? q=servlets 26
POST Example <form method="post" action="http: //www. google. com/search"> <p><input name="q" type="text" /> <input type="submit" /> <input type="reset" /> </p> Google doesn’t </form> support POST! POST /search HTTP/1. 1 Host: www. google. com … Content-type: application/x-www-form-urlencoded Content-length: 10 <empty-line> q=servlets 27
Getting the Parameter Values • To get the (first) value of a parameter named x: - req. get. Parameter("x") where req is the service request argument • If there can be multiple values for the parameter: - req. get. Parameter. Values("x") • To get parameter names: - req. get. Parameter. Names() 28
<html><head><title>Sending Parameters</title> <style type="text/css"> p{display: table-row} span{display: table-cell; padding: 0. 2 em} </style></head><body> <h 1>Please enter the parameters</h 1> <form action=“setcolors" method="get"> <p>Background color: <span><input type="text" name="bgcolor"/></span></p> <p>Font color: <span><input type="text" name="fgcolor"/> </span> </p> <p>Font size: <span><input type="text" name="size"/></span></p> <h 2> <input type="submit" value="Submit Parameters"/></h 2> </form> </body></html> parameters. html 29
An Example (cont( public class Set. Colors 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 bg = request. get. Parameter("bgcolor"); String fg = request. get. Parameter("fgcolor"); String size = request. get. Parameter("size"); Set. Colors. java 30
An Example (cont( out. println("<html><head><title>Set Colors Example" +"</title></head>"); out. println("<body style="color: " + fg + "; background-color: " + bg + "; font-size: "+ size + "px">"); out. println("<h 1>Set Colors Example</h 1>"); out. println("<p>You requested a background color " + bg + "</p>"); out. println("<p>You requested a font color " + fg + "</p>"); out. println("<p>You requested a font size " + size + "</p>"); out. println("</body></html>"); } Set. Colors. java 31
Handling Post • You don't have to do anything different to read POST data instead of GET data!! <form action="localhost/dbi/Set. Colors" method="post"> … public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(request, response); } 32
Creating the Response of the Servlet 33
HTTP Response • The response includes: Ø Status line: version, status code, status message Ø Response headers Ø Empty line Ø Content HTTP/1. 1 200 OK Content-Type: text/html Content-Length: 89 Server: Apache-Coyote/1. 1 <HTML><HEAD><TITLE>HELLO WORLD</TITLE></HEAD> <BODY><H 1>Hello World </H 1></BODY></HTML> Read more about the Http. Response Interface 34
Setting the Response Status • Use the following Http. Servlet. Response methods to set the response status: - set. Status(int sc) • Use when there is no error, like 201 (created) • No need to send 200 OK explicitly… - send. Error(sc), send. Error(sc, message) • Use in erroneous situations, like 400 (bad request) • The server may return a formatted message - send. Redirect(String location) • As opposed to forwarding which is done within the server side completely, on redirect the client gets the “Location” header and a special code (302) and sends another request to the new location 35 http: //localhost/dbi/redirect
Setting the Response Status • Class HTTPServlet. Response has static integer variables for popular status codes - for example: SC_OK(200), SC_NOT_MODIFIED(304), SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400) • Status code 200 (OK) is the default 36
Setting Response Headers • Use the following HTTPServlet. Response methods to set the response headers: - set. Header(String hdr, String value), set. Int. Header(String hdr, int value) • Override existing header value - add. Header(String hdr, String value), add. Int. Header(String hdr, int value) • The header is added even if another header with the same name exists 37
Specific Response Headers • Class HTTPServlet. Response provides setters for some specific headers: - set. Content. Type - set. Content. Length • automatically set if the entire response fits inside the response buffer - set. Date. Header - set. Character. Encoding 38
More Header Methods • contains. Header(String header) - Check existence of a header in the response • add. Cookie(Cookie) • send. Redirect(String url) - automatically sets the Location header • Do not write into the response after send. Error or send. Redirect Check the result of writing a response after send. Error/send. Redirect http: //localhost/dbi/bad. html 39
The Response Content Buffer • The response body is buffered • Data is sent to the client when the buffer is full or the buffer is explicitly flushed • Once the first data chunk is sent to the client, the response is committed - You cannot set the response line nor change the headers. Such operations are either ignored or cause an exception to be thrown Check the result of send. Error/set. Content. Type getting “commited” http: //localhost/dbi/bad. html 40
Buffer Related Methods • set. Buffer. Size, get. Buffer. Size - What are the advantages of using big buffers? what are the disadvantages? • flush. Buffer • reset. Buffer - Clears the body content • reset - Clears any data that exists in the buffer as well as the status code and headers • is. Committed 41
Supporting HTTP Methods 42
The HEAD Method • The simplementation of do. Head is executing do. Get and excluding the response body • In addition, the size of the body is calculated and added to the headers • You do not have to override this method • Why would one want to override this method? - The content size is not calculated in servlets as opposed to static html resources… Check the default implementation of do. Head: Run Check. Request. Servlet <HOST> /dbi/init <PORT> GET Run Check. Request. Servlet <HOST> /dbi/init <PORT> HEAD Run Check. Request. Servlet <HOST> /dbi/Time. html <PORT> HEAD (shorter output yet its length is calculated…) In class HOST=localhost, PORT=80 43
The HEAD Method (cont) • The right way to implement do. Head is : - Don’t implement do. Head explicitly - Instead, check within the do. Get call, what is the requested method (http. Servlet. Request. get. Method()) - If it’s HEAD do the same without returning the content - This way the results of HEAD / GET requests are similar as they should be 44
OPTIONS and TRACE • do. Options returns the supported methods: - For example, if you override do. Get then the following header will be returned: Allow: GET, HEAD, TRACE, OPTIONS • do. Trace returns the request itself in the body of the message, for debugging purposes • You usually do not override these methods - Override do. Options if you offer some new methods… 45
Unsupported Methods • By default, the methods do. Post, do. Get, do. Put and do. Delete return an error status code 405 with the message: HTTP method XXX is not supported by this URL • do. Head calls do. Get and therefore leads to the same result but with unsupported method GET • In particular, you have to override do. Get and do. Post if you want to return an appropriate response for these methods - Many applications support only one of GET/POST 46
Servlet Life Cycle 47
Servlet Life Cycle • When the servlet mapped URL is requested, the server loads the Servlet class and initializes one instance of it • Each client request is handled by the Serlvet instance in a separate thread • The server can remove the Servlet • The Servlet can remain loaded to handle additional requests 48
Servlet Life Cycle • When the Servlet in instantiated, its method init() is begin invoked - External parameters are supplied • Upon a request, its method service() is being invoked • Before the Servlet removal, its method destroy() is being invoked 49
Servlet Life Cycle Calling the init method Servlet Instance Deal with requests: call the service method Destroy the Servlet: call the destroy method Servlet. Config In our case by servlet we Servlet Class refer to any class extending Http. Servlet Garbage Collection 50
Initializing Servlets • The method init has a parameter of type Servlet. Config • Servlet. Config has methods to get external initialization parameters (get. Init. Parameter()) - In Tomcat, these parameters are set in web. xml • To make initializations, override init() and not If we use init() and not init(Servlet. Config) - init() is automatically called by after performing default initializations init(Servlet. Config) how could we obtain a reference to the Servlet. Config ? Read more about the Servlet. Config Interface 51
A web. xml Example <web-app> … <servlet> <servlet-name>Init. Example</servlet-name> <servlet-class>Servlet. Init</servlet-class> <init-param> <param-name>login</param-name> <param-value>snoopy</param-value> </init-param> </servlet> … </web-app> 52
public class Servlet. Init extends Http. Servlet { Calls the method String _login = null; get. Init. Parameter defined within the Calendar _init. Time = null; Servlet. Config interface public void init() throws Servlet. Exception { implemented by _login = get. Init. Parameter("login"); Http. Servlet class _init. Time = new Gregorian. Calendar(); } 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><head><title>Initialization</title><body><h 2>" + "I am the Servlet of <i>" + _login+ "</i><br/>" + "I was initialized at " + _init. Time. get(Calendar. HOUR_OF_DAY) + ": "+ _init. Time. get(Calendar. MINUTE) + ": "+ _init. Time. get(Calendar. SECOND) + "</h 2></body></html>"); }} Servlet. Init. java 53
Loading a Servlet on Startup • A Servlet is usually loaded when it is first being called • You can set Tomcat to load a specific Servlet on startup in the Servlet declaration inside web. xml <servlet> <servlet-name>Init. Example</servlet-name> You can use this element to <servlet-class>Servlet. Init</servlet-class> set the loading order of <load-on-startup/> those servlets which are </servlet> loaded on start 54
Destroying Servlets • The server may remove a loaded Servlet, Why? : - asked to do so by administrator(e. g. Server shutdown) - Servlet was idle a long time - server needs to free resources • The server removes a Servlet only if all threads have finished or a grace period has passed • Before removing, calls the destroy() method - can perform cleanup, e. g. , close database connections • Is it possible for the Servlet to end without its destroy being called? - You can do it if you kill the process explicitly 55
Thread Synchronization • Multiple threads are accessing the same Servlet object at the same time • Therefore, you have to deal with concurrency • init() and destroy() are guaranteed to be executed only once (before/after all service executions) 56
The Servlet Context 57
The Servlet Context Object • A Servlet context represents the Web application that Servlets live in • There is one Servlet context per application • You can get the Servlet context within do. XXX using the method get. Servlet. Context() • The Servlet context has many methods • For example, you can store in it objects that are kept throughout the application's life Read more about the Servlet. Context Interface 58
An Example: Service Count We cannot use int public class Counter. Servlet extends Http. Servlet {since attribute must be an object and not primitive public void init() throws Servlet. Exception { Integer counter = (Integer)get. Servlet. Context(). get. Attribute("counter"); if(counter == null) { get. Servlet. Context(). set. Attribute("counter", new Integer(0)); } The counter might be already initialized, if the server is running but } the instance of Counter. Servlet was removed from the memory. In this case we wouldn’t like to reinitialize the counter with 0. 59
public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { The response’s character encoding cannot be set using this ordering, Print. Writer out = res. get. Writer(); since writer was already created res. set. Content. Type("text/html"); int counter = 0; A new Integer must synchronized(this) { be created since counter = ((Integer)get. Servlet. Context(). an Integer’s get. Attribute("counter")). int. Value(); value cannot be get. Servlet. Context(). modified set. Attribute("counter", new Integer(++counter)); } out. println("<html><head><title>Counter</title><body><h 1>" + "[" + counter + "]</h 1></body></html>"); }} 60
Context Listeners • A context listener is an object that reacts to the following events: - Context initialization - Context destruction • We can use a context listener to perform application initialization or termination tasks • To implement such a listener, - Implement the interface Servlet. Context. Listener - Put the class file in my. App/WEB-INF/classes like all the other classes - Register the listener with the server Read more about the Servlet. Context. Listener Interface 61
Cheating with Service Count public class Counter. Initializer implements Servlet. Context. Listener { public void context. Initialized(Servlet. Context. Event sce) { sce. get. Servlet. Context(). set. Attribute("counter", new Integer(1000)); } public void context. Destroyed(Servlet. Context. Event sce) {} } <web-app> <listener> <listener-class>Counter. Initializer</listener-class> </listener> Uncomment the listener lines in </web-app> web. xml or use web 2. xml 62
Exceptions • Exceptions are caught by the server • You can find them in the log file under $CATALINA_BASE/logs/ • The result shown in the browser depends on the buffer state • Check the example on the next slide… • Find the exceptions in the log 63
public class Exception. Servlet 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(); int n. Lines = Integer. parse. Int(request. get. Parameter("nlines")); out. println("<html><head></head><body>"); for (int i = 0; i < n. Lines; ++i) { out. println("<p> bla bla " + i + "</p>"); } out. println("</body></html>"); out. println(" " + 1/0 + " "); }} This line causes exception Run : http: //localhost/dbi/exception? nlines=1000 64
- Core servlets
- Servlets notes
- Sun grid engine tutorial
- Introduction paragraph structure
- Xxxxxx 2017
- Explain the sun
- Copper sun poem
- Laerdal sun
- Mon tue wed thur fri sat sun
- Moon phases of the sun is on the right
- Seasonal changes diagram
- When earth receives energy from the sun, ____.
- Vray sun ozone
- 3 verbs for sun
- Microprocessor
- Sun transit outage
- How does the sun affect tides
- Assurant in springfield ohio
- Distance from the sun saturn
- What is the core of the sun made of
- What is the sun
- Sun fact sheet
- Does the sun rotate
- The sun still rises in the same sky
- The sun still rises in the same sky
- The rising sun john donne
- The sun rising john donne
- What is the topic of the essay the sun parlor
- How does the sun produce energy
- What is the sun made up of
- What keeps the sun hot
- Characteristics of sun
- Photosphere
- 3 facts about the sun
- The solar system consists of the
- When the sun passes between the moon and earth
- Jaguar poem short summary
- The diagram below shows the path of a comet around the sun
- Why is the sun important
- Sun explosion candy bar
- What is a tessellation?
- Tak sun london
- Symbols in raisin in the sun
- Sun fact file
- How do the sun and moon work together
- Sat tomorrow
- Sun metro lift
- Webappcabaret pricing
- Oea sun direct
- Sun bear life cycle
- 6 layers of the sun
- Dual sun solar system
- Star sun solar
- Peak sun hours
- Solar energy is radiant light and heat
- Peak sun hours
- Star colors from coolest to hottest
- 소네트 130
- North pole sun path
- Sweet flower with flowers thy bridal
- Remains full poem
- The visible light we see from our sun comes from which part
- The sun rises in the east present perfect tense
- Which features of the sun look like huge cloudlike arches
- Close to the sun in lonely lands figurative language