Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

Client Server Communication And Servlets

Loading...

Published in: Networking
5,208 Views

This presentation includes introduction of client server architecture and need of servlets.

Anuja S / Chandigarh

5 years of teaching experience

Qualification: M.Tech (Banasthali Vidyapeeth University - 2012), B.Tech/B.E. (Maharishi Dayanand University - 2010), 12th (HAL School korwa - 2006)

Teaches: Basic Computer, Computer for official job, MS Office, School Level Computer, Computer Science, Mathematics, Physics, PSU Exam, GATE Exam, Computer, IT, Java Script, Web CMS

Contact this Tutor
  1. Client Server Communication Client
  2. > The user enters URL into a browser. The browser generates an HTTP request to the appropriate web server. > The web server maps the request to a specific file. That file is returned in an HTTP content. > The HTTP header in the response indicates the type of the content. The Multipurpose Internet Mail Extensions (MIME) are used for this purpose. For example ASCII text has MIME type of text/plain.
  3. CGI CGI = Common Gateway Interface Defines interface W/eb servers and programs
  4. Why Not CGIs (cont.) Inefficient: new process for each request! ! ! It was also expensive to open and close database connections for each client request. Programs are not platform independent
  5. J2EE 1 tier (No Server required), 2 tier (Client and DB Server) 3 tier (Client, Middle ware, DB Server) N tier 2-tier I-tier Architecture Architecture Core JAVA Program Client DB: Database PL: presentation Logic BL: Business Logic DL: database logic 5 DB 3-tier Architecture Client DB Middle layer
  6. N tier Architecture Browser Browser Applet Application 6 Web Server Servlets JSP RMI Application Server EJB EJB EJB JMS Legacy System DB JNDI RMI/IIOP EJB JDBC Distributed CORBA Objects
  7. N tier Architecture Cont... EJB: Enterprises Java Beans ' JMS: Java Messaging Service ' JNDI: Java Naming and Directory Interface ' JDBC: Java DataBase Connectivity RMI: Remote Method Invocation ' IIOP: Internet Inter ORB Protocol CORBA: Common Object Request Broker Architecture ' JSP: JAVA Server Pages
  8. Web Server Functions of Web Server: Read any data sent by the user. — Look up any other information about the request that is embedded in the HTTP request. Process the request Generate the result. — Format the result inside a document. — Set the appropriate HTTP response parameters. — Send the document back to the client as HTML file. 8
  9. Request and Response Processing http request Web Browser http response 9 Web Server Web application J2EE Web Container Servlet JSP Static Page Static Web Pages
  10. Request and Response Processing HTXP reeves' con tainer• request res User a to •set-vied instead a static peg e The container -sees— It'euat reqt-æst •for a serviet- sc cyaruainer creates two OC4ect5: Tt-e tt•e sers•'gt based on it-e URL request. creates al.Lace1.es a reqL.E€e passes request res.zcse- to 10
  11. Request and Response Processing cont oar.er container ser-vie t serviet serviet Client B•€TTP The contatner tt•e serviees se-viceO mett-•cyd. Depen6ng he type of request- tt•.e serviceO method caes ei&ter the doGet(t or doPost() method. For this assume the was an HTTP GET doGetO generates the eyrarr•ic and stuffs into thre response objecå. tre stili has a reference to response Tt•.e thread cornp'«es. the cor-dær•er the response object an HTTP responæ. sends it back to the dient. tt•en deetes the and response obtecas. 11
  12. Server Side java ' Servlet is a java Technology for server side programming. ' It is a Java module that runs inside a Java enabled web server and services requests obtained from the web server.
  13. Servlet Strengths Efficient: When a servlet gets loaded in the server,it remains in the server memory as a single object instance.Each request is then served by a light weight Java thread spawned from the servlet, which is much more efficient than creating a new process for every request. ' Persistent: Servlets can maintain the session by using session tracking cookies,a mechanism that helps them track information from request to request. ' Portable: Servlets are written in java so they are portable across operating systems and server implementation.
  14. Interface -servle t-s ervle t •i nitO •g e tS et-vle Config O •S ceO •g et S ervle t.InfoO Servlet Architectute Interface j -ser-v-l et- S e IVI etConfig • g et.lni ete • g etS ervl etCot1tex • g e tini e te j avax -set-vl et- Gen eric Se rvlet •g e tPa e te •g e ts Conte x •g e ete •i nitO •g e ts ervle O •S ceO •g e ts ervle •de stroyO -setvl et-http-EttpServ1et •doDe1e teo •doGeeO •doPostO •doOptionsO •doPutO •doTt-a ceO •g e edO •S ex-vic eo —J a Ke - co Interface —Ta&-ax -i o -Se al ble
  15. GENERICSERVLET AND HTTPSERVLET The servlet packages define two abstract classes that implement the interface Servlet—class GenericServIet (from the package javax.servlet) and class HttpServIet (from the package javax.servlet.http). These classes provide default implementations of all the Servlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods. The GenericServlet class defines a generic protocol independent servlet, it can be used to implement any protocol like HTTP,FTP and SMTP. The HTTPServlet class extends GenericServlet and provides framework for handling HTTP requests. It reads the method type stored in the request and invokes a specific method based on this value. doGet(HttpServletRequest req, HttpServletResponse res), doPost(HttpServletRequest req, HttpServletResponse res)
  16. Execution of servlet consists of four steps: The client sends a request to the web server. The web server interprets it and forwards it to the corresponding servlet. The servlet processes the request , generates the output(if any),sends it back to the The web server sends the response back to the client.The browser then displays it on the screen
  17. Servlet Life cycle The container in which the servlet has been deployed supervises and controls the life cycle of a servIet.This container is known as Web Server. After the container receives a request from client,it performs the following steps: 1. If an instance of the target servlet does not exist,the container does the following- a)Finds and loads the servlet class b)Creates an instance of the servlet class c)CaIIs the init() method on this servlet instance to initialize it.
  18. 2)Otherwise, it invokes the service() method on it,passing a servIetRequest and ServIetReponse type object. 3) If the container decides that the servlet is no longer needed,it removes and finalizes the servlet by calling the servlets destroy() method.
  19. The Servlet Life Cycle The init(ServletConfig SC) Method: This method is called only once by the web container,just after it instantiates the servlet is loaded which is ready to handle the clients request.lt passes a Servletconfig object,which contains the startup configuration for this servlet such as initialization parameters. The service(Serv/etRequest req, ServletResponse res) Method: It is called each time the web container receives a request intended for this servlet. The ServletRequest interface provides methods to retrieve information sent by the clients and ServletResponse interface provides methods to send data to the clients. The destroy() Method:lt is called when the web container uninstalls the servlet.lt cleans up the resources and makes sure that any persistent state is synchronized with the servlets current in-memory state. 19
  20. Difference between Applet and servlets. Applets Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers. An Applet is a client side java program that runs within a Web browser on the client machine. An applet can use the user interface classes like AWT or Swing. Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy() Servlets Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server. Servlet is a server side component which runs on the web server. The servlet does not have a user interface. Servlet Methods: doGet(), doPost()
  21. Servlet Execution Steps Web Container Step I Step Il Step Ill Step IV Step V Step VI Step Vll Step Vlll 21 Load class (Class c = Class.forName("MyServlet"); Instantiate Servlet (Servlet s = (Servlet) c.newlnstance()); Web Container construct the ServletConfig object Calling of Method: init(ServletConfig sc) Object Creation: [Http]ServletReqest and [Http]ServletResponse Calling of Method: service( request, response) Repeat Step V & VI Calling of Method: destroy()
  22. Basic Servlet Structure package my.pkg; import java.io.* import javax.servlet.*, import javax.servlet.http.* public class HelloAricent extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("Hello World");}} N etscape File Edit. View Go Bookmarks TJor -Ld Hello 22 Communicator Help Location: http://localhost/'servleWHelloWorld vel Docun
  23. The class for this file resides in INF\classes directory. We need to inform the web server about the exixtence of this servlet and the URL that will be used to refer to this servlet.This is specified in the INF\web.xml file which is the cofiguration XML file for this website.
  24. web.xml HelloWorld HelloAricent HelloWorld /servlet/Helloworld Complete url for this servlet will be: http://localhost:8080/wt/servlet/Helloworld. 24
  25. Simple Example import java.io.*, import java.net.*, import javax.servlet.*, public class genericl extends GenericServIet { public void service(ServIetRequest request, ServIetResponse response) throws ServIetException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {
  26. Simple Example out.println(""); out.println(""); out.printIn("ServIet genericl"); out.println(""); out.println(""); out.printIn("HeIIo "+ ""); out.println(""); "); out.println(" } finally { out.close();
  27. How to run a servlet- Type the following address in the address bar of the browser http://IocaIhost:8080/WebAppIication3/generic1
  28. Javax.servlet package Interface Servlet ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel Description Declares life cycle methods for a servlet Allows servlets to get initialization parameters Enables servlet to log events and access information about their environment Used to read data from a client request Used to write data to a client response Indicates that the servlet is thread safe.
  29. Javax.servlet package Class GenericServlet ServletlnputStream ServletOutputStream ServletException UnavailableException Description Implements the Servlet and ServletConfig interfaces Provides an input stream for reading requests from a client. Provides an output stream for writing responses to a client. Indicates a servlet error occured Indicates a servlet is unavailable.
  30. Javax.servIet.GenericServIet class GenericServIet is an abstract class. >public abstract class GenericServIet implements Servlet, ServIetConfig At provides simple versions of the life-cycle methods init and destroy, and of the methods in the ServIetConfig interface. It also provides a log method, from the ServIetContext interface. The servlet writer must override only the service method, which is abstract.
  31. Constructor of GenericServIet class public GenericServIet() ; The default constructor does no work.
  32. Methods of GenericServIet class 1. public void destroy() Destroys the servlet, cleaning up whatever resources are being held, and logs the destruction in the servlet log file. This method is called, once, automatically, by the network service each time it removes the servlet. After destroy is run, it cannot be called again until the network service reloads the servlet. When the network service removes a servlet, it calls destroy after all service calls have been completed, or a service-specific number of seconds have passed, whichever comes first. In the case of long-running operations, there could be other threads running service requests when destroy is called. The servlet writer is responsible for making sure that any threads still in the service method complete.
  33. Methods of GenericServIet class 2. public void init() throws ServIetException This method is provided as a convenience so that servlet writers do not have to worry about storing the ServIetConfig object.
  34. Methods of GenericServIet class 3. public void init(ServIetConfig config) throws ServIetException Initializes the servlet and logs the initialization. The init method is called once, automatically, by the network service each time it loads the servlet. It is guaranteed to finish before any service requests are accepted.
  35. Methods of GenericServIet class 4. public abstract void service(ServIetRequest req, ServIetResponse res) throws ServIetException, IOException Carries out a single request from the client. The request object contains parameters provided by the client, and an input stream, which can also bring data to the servlet. To return information to the client, write to the output stream of the response object.