1 cs6320 – servlet structure and lifecycle l. grewe
Post on 15-Jan-2016
235 views
TRANSCRIPT
11
CS6320 – Servlet CS6320 – Servlet Structure and LifecycleStructure and Lifecycle
L. GreweL. Grewe
22
The The ServletServlet Interface Interface Java provides the interface Java provides the interface ServletServlet Specific Servlets implement this interfaceSpecific Servlets implement this interface Whenever the Web server is asked to invoke Whenever the Web server is asked to invoke
a specific Servlet, it activates the method a specific Servlet, it activates the method service()service() of an instance of this Servletof an instance of this Servlet
service(request,response)
MyServlet
(HTTP)request
(HTTP)response
33
Example – Generic ServletExample – Generic Servletimport java.io.*; import java.io.*; import java.servlet.*; import java.servlet.*; public class HelloWorldServlet extends GenericServlet public class HelloWorldServlet extends GenericServlet
{ {
public void service(ServletRequest req, ServletResponse res) public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException{ throws ServletException, IOException{ PrintStream out = newPrintStream(res.getOutputStream()); PrintStream out = newPrintStream(res.getOutputStream()); out.println("Hello world!"); out.println("Hello world!"); } }
public String getServletInfo() { public String getServletInfo() { return "Hello World Servlet"; return "Hello World Servlet"; } }
} }
44
Servlet HierarchyServlet Hierarchy
YourOwnServlet
HttpServlet
Generic Servlet
Servletservice(ServletRequest,
ServletResponse)
doGet(HttpServletRequest , HttpServletResponse)
doPost(HttpServletRequest HttpServletResponse)
doPutdoTrace
…
55
HTTP Request MethodsHTTP Request Methods
POSTPOST -- application data sent in the application data sent in the request bodyrequest body
GETGET - application data sent in the URL- application data sent in the URL HEADHEAD - client sees only header of - client sees only header of
response response PUTPUT - place documents directly on server - place documents directly on server DELETEDELETE - opposite of PUT - opposite of PUT TRACETRACE - debugging aid - debugging aid OPTIONSOPTIONS - list communication options - list communication options
66
Class Class HttpServletHttpServlet Class Class HttpServletHttpServlet handles requests and handles requests and
responses of HTTP protocolresponses of HTTP protocol The The service()service() method of method of HttpServletHttpServlet checks checks
the request method and calls the the request method and calls the appropriate appropriate HttpServletHttpServlet method: method:
doGetdoGet,, doPost doPost, , doPutdoPut, , doDeletedoDelete, , doTracedoTrace, , doOptionsdoOptions or or doHead doHead
This class is abstractThis class is abstract
77
Creating a ServletCreating a Servlet Extend the classExtend the class HTTPServletHTTPServlet Implement Implement doGetdoGet or or doPostdoPost (or both)(or both) Both methods get:Both methods get:
• HttpServletRequestHttpServletRequest:: methods for getting form methods for getting form (query) data, HTTP request headers, etc.(query) data, HTTP request headers, etc.
• HttpServletResponseHttpServletResponse:: methods for setting methods for setting HTTP status codes, HTTP response headers, HTTP status codes, HTTP response headers, and get an output stream used for sending and get an output stream used for sending data to the clientdata to the client
Many times, we implementMany times, we implement doPostdoPost by by calling calling doGetdoGet, or vice-versa, or vice-versa
88
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TextHelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Hello World");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doGet(req, res);
}
}
HelloWorld.java
99
The Response: Returning HTMLThe Response: Returning HTML
By default, no content type is given By default, no content type is given with a responsewith a response
In order to generate HTMLIn order to generate HTML• Tell the browser you are sending HTML, by Tell the browser you are sending HTML, by
setting the setting the Content-TypeContent-Type header header• Modify the printed text to create a legal Modify the printed text to create a legal
HTML pageHTML page You should set all headers You should set all headers beforebefore
writing the document content.writing the document content. Can you Can you guess why?guess why?
1010
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello World</title></head>\n");
out.println("<body>");
out.println("<h2>" + new java.util.Date() + "</h2>\n");
out.println("<h1>Hello World</h1>\n</body></html>"); }
}
HelloWorld.java
1111
Life of a ServletLife of a Servlet
Birth: Create and initialize the Birth: Create and initialize the servletservlet Important method: init()Important method: init()
Life: Handle 0 or more client Life: Handle 0 or more client requestsrequests Important methods: service(), doGet(), Important methods: service(), doGet(),
and doPost().and doPost(). Death: Destroy the servletDeath: Destroy the servlet
Important method: destroy() Important method: destroy()
1212
Servlet Life CycleServlet Life Cycle
Servlet Class
Calling the init method
Servlet Instance
Deal with requests:call the
service method
Destroy the Servlet: call the
destroy method
Garbage Collection
ServletConfig
1313
The init() methodThe init() method The init() method is called when the servlet is The init() method is called when the servlet is
first requested by a browser request.first requested by a browser request. It is It is notnot called again for each request. called again for each request. Used for Used for one-time initializationone-time initialization.. The method The method initinit is overloadedis overloaded and has a and has a
parameter of type parameter of type ServletConfigServletConfig ServletConfigServletConfig h has methods to get external as methods to get external
initialization parameters initialization parameters • In Tomcat, these parameters are set in In Tomcat, these parameters are set in web.xmlweb.xml
To make initializations, override To make initializations, override init()init() and notand not init(ServletConfig) init(ServletConfig) • init()init() is automatically called by after performing is automatically called by after performing
default initializationsdefault initializations
1414
Service() MethodService() Method
Each time the server receives a request for a Each time the server receives a request for a servlet, the server spawns a new thread and calls servlet, the server spawns a new thread and calls the servlet’s service () method.the servlet’s service () method.
Browser
Browser
Browser Web Server Single Instanceof Servlet
service()
service()
service()
1515
The Service MethodThe Service Method
By default the service() method checks the By default the service() method checks the HTTP Header.HTTP Header.
Based on the header, service calls either Based on the header, service calls either doPost() or doGet().doPost() or doGet().
doPost and doGet is where you put the doPost and doGet is where you put the majority of your code.majority of your code.
If your servlets needs to handle both get If your servlets needs to handle both get and post identically, have your doPost() and post identically, have your doPost() method call doGet() or vice versa.method call doGet() or vice versa.
1616
Thread SynchronizationThread Synchronization
By default, multiple threads are accessing By default, multiple threads are accessing the same servlet object at the same time.the same servlet object at the same time.
You therefore need to be careful to You therefore need to be careful to synchronize access to shared data.synchronize access to shared data.
For example, the code on the next slide For example, the code on the next slide has a problem…has a problem…
1717
package coreservlets;
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class UserIDs extends HttpServlet { private int nextID = 0; public void doGet(
HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your ID"; String docType = … String id = "User-ID-" + nextID; out.println("<H2>" + id + "</H2>"); nextID = nextID + 1; out.println("</BODY></HTML>"); }}
This code is problematic. Can result in a race condition, where two users can actuallyget the same User-ID!
For example:
User 1 makes request:
String id = "User-ID-" + nextID; Gets nextId of 45.
Now User 2 makes request,and pre-empts user 1:
String id = "User-ID-" + nextID; Gets nextId of 45 (same one!)
Admittedly, this case is rare,but it’s especially problematic.Imagine if user Id was tied tocredit card number!
1818
How to Solve Synchronization ProblemsHow to Solve Synchronization Problems
You have a few options for solving You have a few options for solving servlet synchronization issues:servlet synchronization issues:
1)1) Never use instance variables (or protect Never use instance variables (or protect them) in your servlets…use local variables. If them) in your servlets…use local variables. If you don’t have shared instance variables, you don’t have shared instance variables, you don’t have shared synchronization you don’t have shared synchronization problems.problems.
2)2) Synchronize code explicitly with Java Synchronize code explicitly with Java synchronization blocks.synchronization blocks.
3)3) Note recommended - Use the Note recommended - Use the SingleThreadInterface SingleThreadInterface
1919
Java SynchronizationJava Synchronization
Use a synchronization block whenever Use a synchronization block whenever accessing/modifying a shared variable.accessing/modifying a shared variable.
For example:For example:
synchronized (this) {synchronized (this) {String id = "User-ID-" + nextID;String id = "User-ID-" + nextID;out.println("<H2>" + id + "</H2>");out.println("<H2>" + id + "</H2>");nextID = nextID + 1;nextID = nextID + 1;
}}
2020
SingleThreadModel InterfaceSingleThreadModel Interface To prevent multi-threaded access, you can have your To prevent multi-threaded access, you can have your
servlet implement the SingleThreadModel:servlet implement the SingleThreadModel:public class YourServlet extends HttpServlet implements public class YourServlet extends HttpServlet implements
SingleThreadModel {SingleThreadModel {……
}} This will guarantee that your servlet will only process one This will guarantee that your servlet will only process one
browser request at a time.browser request at a time. It therefore addresses most synchronization issues.It therefore addresses most synchronization issues. Unfortunately, however, it can result in severe slowing of Unfortunately, however, it can result in severe slowing of
performance, and most people performance, and most people strongly recommend against strongly recommend against using it.using it.
In fact, the SingleThreadModel interface is now deprecated In fact, the SingleThreadModel interface is now deprecated in the Servlet 2.4 API.in the Servlet 2.4 API.
2121
Death of a ServletDeath of a Servlet Before a server shuts down, it will call the Before a server shuts down, it will call the
servlet’s destroy() method.servlet’s destroy() method. You can handle any servlet clean up here. For You can handle any servlet clean up here. For
example:example: Updating log files.Updating log files. Closing database connections.Closing database connections. Closing any socket connections.Closing any socket connections.
The server may remove a loaded Servlet, Why?:The server may remove a loaded Servlet, Why?:• asked to do so by administrator(e.g. Server shutdown)asked to do so by administrator(e.g. Server shutdown)• Servlet was idle a long timeServlet was idle a long time• server needs to free resourcesserver needs to free resources
The server removes a Servlet only if all threads The server removes a Servlet only if all threads have finished or a have finished or a grace period grace period has passedhas passed
2222
Example: Persistent CounterExample: Persistent Counter
To create a persistent record, we can To create a persistent record, we can store the count value within a store the count value within a “counter.txt” file.“counter.txt” file. init(): Upon start-up, read in the current init(): Upon start-up, read in the current
counter value from counter.txt.counter value from counter.txt. destroy(): Upon destruction, write out destroy(): Upon destruction, write out
the new counter value to counter.txtthe new counter value to counter.txt
2323
import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;
public class CounterPersist extends HttpServlet { String fileName = "counter.txt"; int count;
public void init () {try { FileReader fileReader = new FileReader (fileName); BufferedReader bufferedReader = new BufferedReader (fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt (initial);} catch (FileNotFoundException e) { count = 0; }
catch (IOException e) { count = 0; } catch (NumberFormatException e) { count = 0; }
}
At Start-up, load the counter from file.In the event of any exception, initializecount to 0.
Continued….
2424
// Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/plain");PrintWriter out = response.getWriter();count++;out.println ("Since loading, this servlet has "
+"been accessed "+ count + " times.");out.close();
} Each time the doGet() method is called, increment the count variable.
Continued….
2525
// At Shutdown, store counter back to file public void destroy() {
try {FileWriter fileWriter = new FileWriter (fileName);String countStr = Integer.toString (count);fileWriter.write (countStr);fileWriter.close();
} catch (IOException e) {e.printStackTrace();
} }}
When destroy() is called, store new counter variable back to counter.txt.
Any problems with this code?