Fast Track Revision on Servlet Introduction & Life Cycle Designed By: www.interviewDuniya.com Prerequisites For this section you are expected to know Java programming including: while and for loops (vital) if (vital) Passing parameters to methods (vital) Arrays and Strings (important) The Enumeration class (important) Threads and synchronized (useful) Exceptions try and catch (useful) www.interviewDuniya.com Serving Static HTML Web servers where designed to provide web browsers with HTML. The HTML was read from text files by the server and sent to the client using HTTP. The web server does not modify the HTML. This is now termed static HTML serving HTML doGet or doPost Server Machine Web Server HTML Client Machine Web Browser HTML Web Page on disk www.interviewDuniya.com Static HTML the Problem •Modern uses of web pages often require pages to be dynamically generated. •For example a chat system would display any new messages each time you hit refresh. This requires the web page the browser requests to be modified each time someone adds a new message. •Until recently there was no easy way to do this because • web browsers were not designed to rewrite web pages • web browsers are stateless so they process each request in isolation without reference or memory of what request came before it. www.interviewDuniya.com Why servlets over CGI script? A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request. A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request. Perl 1 Browser 1 Browser 2 Browser N Web Server Perl 2 Perl N There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data. Browser 1 Browser 2 Browser N Web Server Servlet A Servlet can be run by a Servlet Engine in a restrictive Sandbox (just like an Applet runs in a Web Browser's Sandbox) which allows secure use of untrusted and potentially harmful Servlets. www.interviewDuniya.com What can you build with Servlets? Search Engines Personalization Systems E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications: bulletin boards, file sharing, etc. www.interviewDuniya.com on the web server and communicate using with the web browser using HTTP and HTML Servlets are compatible with all web browsers because servlets communicate with the browser using only HTML and HTTP Servlets are simple to write because they are written in standard Java Most of the communication is done for you by the Servlet class. No need to mess around with Sockets, TCP/IP or Java serialisation. Servlets - a solution for dynamically generating HTML in Java which run Servlets are programs written www.interviewDuniya.com 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 www.interviewDuniya.com A Servlet is a Java class that extends the web server's service capabilities. When the client sends a request to the server the. Server can forward the request to a Servlet and let it handle the request. Servlets provide open, cross-server and OS APIs. Servlets have a clean design; This leads to simplicity. Servlets live inside a Servlet Container. www.interviewDuniya.com What Is a Servlet Container Sometimes called a Servlet Engine. The Servlet Container provides Servlets with the environment, configuration and runtime needed to support the Servlet APIs: Load the Servlets. Initialize the Servlets. Execute the Servlets. Destroy the Servlets. Servlets do not have a main… The container have it… www.interviewDuniya.com A Java Servlet Sending a request and receiving a response www.interviewDuniya.com Who Backs Servlets? Servlets are backed by "anybody but Microsoft." There is Servlets support for virtually all common servers (including Microsoft's). Supporting Servlets can be done in one of two ways: Supporting the Servlet APIs in the web-server level Adding a Servlet-Container add-on to the web-server. www.interviewDuniya.com Function Cycle of a Servlet 1.) A user clicks submit of a form using a servlet 2.) The data in the form is sent to the server 3.) The server finds the appropriate servlet 4.) The servlet creates the HTML page based on the user’s supplied information 5.) The created HTML page is then transmitted back to the user 6.) The requested information is displayed in the user’s web browser www.interviewDuniya.com Servlet Life Cycle Loaded in memory of the web server Servlet resides in memory until called by the server Computes requested information Returns to idle state in memory Servlet is destroyed www.interviewDuniya.com The Basic Structure of an HttpServlet There are several methods that you commonly override when you write an HttpServlet. These methods are www.interviewDuniya.com void init(ServletConfig sc) throws ServletException; void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; www.interviewDuniya.com The Servlet Lifecycle www.interviewDuniya.com The Servlet life-cycle defines: How a Servlet is initialized. How a Servlet is serving users and how many times. How a Servlet is destroyed. Concurrency management (multi-threading considerations). www.interviewDuniya.com In brief…the sequence of events.. The sequence of events starts with a browser sending a request to a Web server. The server hands the request to a Servlet Container. The container loads the servlet (if it isn't already loaded), instantiates a request and response objects, and then hands these objects to the servlet by calling first its init() method, then its service() method, and lastly the destroy() method. The service() method will typically call one of the doXXX() methods such as doGet(). www.interviewDuniya.com Servlet Instantiation The container instantiates a new Servlet in two occasions: A user request service from a Servlet that was not instantiated yet. The Servlet is in the list of startup Servlets and the container is starting. A Servlet is instantiated in the following manner: The container loads the Servlet’s class. Using Class.newInstance() the container instantiates a new instance of the Servlet. www.interviewDuniya.com Servlet Initialization After the instantiation, the container initializes the Servlet. The container casts the new instance to a Servlet object and initializes it by calling an init() method. If initialization fail the Servlet creation fail and the new instance is garbage collected. The Servlet initialization is done in a single threaded manner. www.interviewDuniya.com Init() The init method is called when the servlet is first created; init(ServletConfig) or init() it is not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets. www.interviewDuniya.com Init() … A code for initialization that is called only once (e.g., creating the tables of the database) Initialization parameters are server specific Many times these parameters are used to specify the maximum or minimum number for your Servlet. For example, if you have a banking account, there is typically a minimum amount required to maintain the account. The initial parameter could be set to this minimum number and then your Servlet could access it to check the object's value www.interviewDuniya.com Service Phase After the Servlet initialization, the container can ask the Servlet to serve incoming requests. The container will call the Servlet’s service() method. A Servlet may handle many concurrent requests. By different threads, all of them running in the same service methods. The service method should be thread safe. Multithreading By default the servlet need to be multithread safe! One may instruct the container to make the servlet “multithread safe” by insuring that no two thread will execute on a single servlet instance By making the Servlet class implement the SingleThreadModel interface (deprecated) www.interviewDuniya.com singlethreadmodel javax.servlet When we implement singlethreadmodel it means that only one thread can access the service method at a time www.interviewDuniya.com Http Methods when u click on Submit on your JSP page...you will be directed to the method either doGet() or doPost() in the servlet www.interviewDuniya.com 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 The amount of query information is usually limited to 1KB. www.interviewDuniya.com The main diff in these methods When you select GET as method in your form the data you pass from that JSP, will be appended to the URL with your servlet address....... where if you select POST then, any kind of data will not be appended to the URL........it will be passed directly(but u can not see appended data on the URL) www.interviewDuniya.com 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 www.interviewDuniya.com HttpServlet Request Handling Web GET request Server HttpServlet subclass doGet() response service() POST request doPost() response www.interviewDuniya.com Destroying Servlets Destroying: destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet. destroy() method make sure all service threads complete www.interviewDuniya.com End of servlet life cycle www.interviewDuniya.com Servlet Architecture A servlet is an object of the javax.servlet class. It runs inside a Java Virtual Machine on a server host. A servlet is an object. It is loaded and runs in an object called a servlet engine, or a servlet container. Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes – javax.servlet.GenericServlet – javax.servlet.http.HttpServlet www.interviewDuniya.com Working with Servlets www.interviewDuniya.com 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 ServletRequest ServletResponse www.interviewDuniya.com Architecture Servlet Generic Servlet HttpServlet YourOwnServlet www.interviewDuniya.com Generic Servlet & HTTP Servlet Client request Server response service ( ) GenericServlet Browser request HTTP Server response HTTPServlet doGet( ) service ( ) doPost( ) www.interviewDuniya.com Difference between GenericServlet and HttpServlet GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets.(future growth specs) GenericServlet is protocol independent, whereas HttpServlet is protocol dependent In GenericServlets you cannot use Cookies or HttpSession. www.interviewDuniya.com Session tracking is not possible, redirection is not possible. Http servlets overrides doGet and doPost methods. Generic servlet overides service method. generic servlet is superclass for HttpServlet. httpservlet class can also have service() method.it's not necessary that you can only have doGet() and doPost() method defined. Generic servlet is used for small data transfer whereas HttpServlet is used for huge data transfer. www.interviewDuniya.com Writing a Servlet Your servlets will usually extend the HttpServlet class. Which provides default implementations of init, you only need to override this if you want to do some initialisation such as open a database connection. destroy, you only need to override this if you want to do some cleaning up such as closing a database connection. service, should not normally be overridden because it decides which of the doX methods should be called www.interviewDuniya.com Writing a Servlet.. doGet. HTTP Get is the default way a web browser makes a request and this causes the doGet method of the servlet to be invoked so you would normally override this method doPost. If you don't respond to a Post you don't need to override this method. www.interviewDuniya.com •The main differences between Get and Post are data is sent as a query string client query is completely embedded in the URL sent to the server. The amount of query information is usually limited to 1KB. This information is stored in the request line. This is the default method when you click on a href HTML link. * POST: data is sent as part of the message body. Data is not visible in the URL and large amounts of data can be sent to the server. * GET: HTTP Get or Post? www.interviewDuniya.com Servlet doGet and doPost doGet and doPost have identical signatures and receive two parameters from the service method.. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException www.interviewDuniya.com • HttpServletRequest is an Object containing information about the request from the web browser. Such as the login name of the user and any values in the header field sent by the web browser. Any parameters sent as part of the request Any initialisation parameters set in the deployment descriptor It also supplies any session and cookies (more on these later) • HttpServletResponse is an Object which allows you to add cookies, add header values and redirect to a new URL, write HTTP to the web browser and send error messages. www.interviewDuniya.com Client-Server Interaction HTTP Request (Sending request message to Server ): • • When a client sends a request, it consists of three parts: HTTP is a request-response protocol • request line: • HTTP method type (GET or POST) • resource name (URL) • protocol/version e.g. POST /im51p/w7.html HTTP/1/1 • header variables: contains browser information (optional) • message body: in POST method request information is stored here (optional) www.interviewDuniya.com HTTP Response (Sending response message to client): • The response sent by the server also consists of three parts: • response line (server protocol and status code) • header variables (server and response information) • message body (response, such as HTML) www.interviewDuniya.com Servlet Output Request contains any parameters, Cookies and Sessions send by the client Response allows you to add cookies and send data to the client public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { The servlet must get the response.setContentType("text/html"); communications channel from the response Object and set the PrintWriter out = response.getWriter(); out.println(""); out.println("
First Servlet program"); out.println(""); out.println("
Welcome to Servlets
"); out.println(""); out.println("");
First Servlet Program out.close(); }
Welcome to Servlets
www.interviewDuniya.com encoding before sending anything to the client First Servlet Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; Servlets are not part of the standard SDK, they are part of the J2EE Servlets normally extend HttpServlet public class ServWelcome extends HttpServlet The response to be sent to the { client public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException Details of the HTTP request { response.setContentType("text/html"); from the client Set the response type to PrintWriter out = response.getWriter(); text/html (this is normal) } } out.println(""); out.println("
First Servlet Program"); This HTML out.println(""); text is sent to out.println("
Welcome to Servlets
"); out.println(""); the client Don't forget to out.println(""); out.close(); close the www.interviewDuniya.com connection with the client Servlet Life Cycle Managed by the Server and Container // load the servlet class and setup request, response objects Servlet servlet = … ServletRequest request = … ServletResponse response = … // initialise servlet ServletConfig config = servlet.getServletConfig(); servlet.init(config); // service zero or more requests while ( …more requests… ) // invoke servlet to process request servlet.service(request, service); // cleanup after service servlet.destroy(); Call to methods doGet(), doPost() in the user defined servlet class Unlike CGI a single servlet can service several requests. In CGI, a separate process for each request. Servlets therefore reduce s www.interviewDuniya.com Scalability of Servlets There are several costs associated with loading and executing user supplied code in the web server. Compiling and loading Handling sequential requests Handling concurrent requests The servlet is only recompiled by the web browser if it has changed otherwise the already compiled .class file is loaded => Faster response times because the servlet does not need to be recompiled The servlet can be kept in memory for a long time to service many sequential requests => Faster response times because the servlet does not need to be reloaded Only one copy of the servlet is held in memory even if there are multiple concurrent requests for it => less memory usage for concurrent requests and no need to load another copy of the servlet and create a new process to run it. www.interviewDuniya.com 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 www.interviewDuniya.com Calling the Servlet Calling the servlet is done from the Web browser: http://host:port/servlet/ServletName For servlets that are positioned under webapps/ROOT/WEB-INF/classes www.interviewDuniya.com Calling the Servlet Calling the servlet is done from the Web browser: http://host:port/dirName/servlet/ServletName For servlets that are positioned under dir_path/WEB-INF/classes and dir_path is mapped to dirName www.interviewDuniya.com Packages Add packege packageName to the java code to create a package Put the classes files under tomcat_home/webapps/ROOT/WEBINF/classes/packageName Call the servlet with http://host:port/servlet/packageName.servletNa me www.interviewDuniya.com The Servlet API www.interviewDuniya.com What’s in the APIs The Servlet APIs defines: A servlet lifecycle – how a servlet is created, used and destroyed. A programmer interface – how a servlet looks like to the container and how the container looks like to the servlet. The Servlet APIs is what the programmer should care about www.interviewDuniya.com A Destroy Example public void destroy() { /* Check to see whether there are still * service methods running, * and if there are, tell them to stop. */ if (numServices() > 0) { setShuttingDown(true); /* Wait for the service methods to stop. */ while(numServices() > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) {} } } } www.interviewDuniya.com Servlet Destruction A container may destroy the Servlet because: It wants to preserve resources (this is not common). The container is shutting down. In both cases the container will call the Servlet’s destroy() method. Note that this means that a certain Servlet will usually stay “alive” for a very long time and is going to serve many users. After the destruction the Servlet is garbage collected. www.interviewDuniya.com Supporting Servlets The Web server must support servlets: Apache Tomcat Sun’s JavaServer 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 … www.interviewDuniya.com “Listening” to a Shutdown public void doPost(...) { ... for(i = 0; ((i < numberOfThingsToDo) && !isShuttingDown()); i++) { try { partOfLongRunningOperation(i); } catch (InterruptedException e) {} } } www.interviewDuniya.com Passing Multiple Parameters to Servlets To pass more than one parameter separate each one with a &
click here for a parameter example! The value of the parameter The name of the parameter The value of the parameter The name of the www.interviewDuniya.com parameter Getting a list of Parameters You can get a list of all the parameters passed by using getParameterNames() which returns an Enumeration Object Enumeration p=request.getParameterNames(); while (p.hasMoreElements()) { String n=(String)p.nextElement(); String v=request.getParameter(n); out.println("parameter name is "+n+" parameter value" +v+"
"); } www.interviewDuniya.com Using forms to Pass Parameters The second way to pass parameters to an servlet is This will cause the doGet to use HTML forms. method in the servlet to
is whatever is typed into the text box www.interviewDuniya.com Using Choice boxes The choice box allows one of a set of choices to be selected Just like a TEXT input the result of the selection is stored in a parameter and passed to your application www.interviewDuniya.com Using Choice boxes The code is a little more complex than a TEXT field.
When the submit button is pressed the parameter q0 will have the value 0 or 1 or 2 or 3 www.interviewDuniya.com Using Choice boxes You may have one than one independent choice box in the same form. The result of each select is passed as separate parameters. www.interviewDuniya.com Using Choice boxes In this case one choice is called q0 and the second q1
www.interviewDuniya.com Thread Unsafe import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet { int count=0; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("
Thread UNSAFE example "); out.println(""); out.println("
old count is "+count+"
"); Read then count=count+1; try { Thread.sleep(4000); } catch (Exception e) { } modify then out.println("
new count is "+count+"
"); write out.println(""); out.println(""); } } www.interviewDuniya.com Thread Safe A good way to make sure servlets are thread safe is to have no global data. But this is not always practical. A partial solution is to store data on a per client basis. But this requires sessions or cookies. It does not work if one client machine has two instances of the web browser accessing the servlet concurrently The best method is to mark the sections of code that access global data as synchronized. This allows the sections that do not access global data to run concurrently www.interviewDuniya.com import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet { int count=0; Object s=new Object(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("
Thread UNSAFE example "); out.println(""); synchronized (s) { Can not be out.println("
old count is "+count+"
"); count=count+1; executed try { Thread.sleep(4000); } catch (Exception e) { } concurrently out.println("
new count is "+count+"
"); } out.println(""); out.println(""); } www.interviewDuniya.com } Enclose sections that use global data in synchronized sections Thread Safe Servlets vs. JSP • JSPs – Look like standard HTML or XHTML • Normally include HTML or XHTML markup – Known as fixed-template data – HTML codes can be written easily – Used when content is mostly fixed-template data • Small amounts of content generated dynamically • Servlets – HTML codes have to be written to the PrintWriter or OutputStream – Used when small amount of content is fixed-template data • Most content generated dynamically www.interviewDuniya.com Summary The servlet life cycle? Each servlet has the same life cycle: A server loads and initializes the servlet (init()) The servlet handles zero or more client requests (service()) The server removes the servlet (destroy()) (some servers do this step only when they shut down) www.interviewDuniya.com End of Servlets Basics and Servlets Life Cycle www.interviewDuniya.com