SERVLETS
Servlet• Platform-    independent    Server   side  components , written in Java which  extends the standard web server an...
Servlet Container        The servlet containeris a part of a Web server orapplication      server    thatprovides       th...
Servlet API
javax.servlet.GenericServlet• Signature: public abstract class GenericServlet extends  java.lang.Object implements Servlet...
javax.servlet.http.HttpServlet• Signature: public abstract class HttpServlet extends  GenericServlet implements java.io.Se...
Servlet Life CycleThe Web container manages the life cycle of servlet instances                                        New...
The init ( ) method•    Called by the Web container when the servlet instance is first created•    The Servlets specificat...
The service ( ) method• Called by the Web container to process a user request• Dispatches the HTTP requests to doGet(…),  ...
The destroy() Method•   Called by the Web container when the servlet instance is being eliminated ( All    threads within ...
servletConfig• Object of servletConfig used to pass initialization and  context information to servlets• getServletConfig ...
ServletContext• The javax.servlet.ServletContext interface provides a set of methods  that the servlet can use to communic...
Http Request and Response            Structure• HTTP is a stateless protocol.• Server does not have the overhead of tracki...
Http TransactionsA single request or response line  – <HTTP Method>/<document address>HTTP/    <Version No> e.g.  – GET /i...
Http Servlet Methods•   doGet()•   doPost()•   doHead()•   doDelete()•   doOptions()•   doPut()•   doTrace()•   getLastMod...
Http Servlet Request• getMethod()    – Returns get/post with which request was made.•   getQueryString()•   getRemoteUser(...
Http Servlet Response• addCookie(Cookie)  – Add cookie to response• encodeUrl(String)• sendRedirect(String)• sendError(int)
Thread Safety• Multithreaded = one servlet, multiple  requests simultaneously• Thread safe – not using class variables  si...
Servlets
Servlets
Upcoming SlideShare
Loading in …5
×

Servlets

971 views
927 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
971
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
39
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Servlets

  1. 1. SERVLETS
  2. 2. Servlet• Platform- independent Server side components , written in Java which extends the standard web server and provide a general framework for services build on the Request –Response paradigm• An Efficient and Powerful technology for creating dynamic content for the Web and fundamental part of all Java web technologies
  3. 3. Servlet Container The servlet containeris a part of a Web server orapplication server thatprovides the networkservices over whichrequests and responsesare sent, decodes MIME-based requests, and formatsMIME-based responses. Aservlet container alsomanages servlets throughtheir lifecycle.
  4. 4. Servlet API
  5. 5. javax.servlet.GenericServlet• Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable• GenericServlet defines a generic, protocol-independent servlet.• GenericServlet gives a blueprint and makes writing servlet easier.• GenericServlet implements the log method, declared in the ServletContext interface.• To write a generic servlet, it is sufficient to override the abstract service method.
  6. 6. javax.servlet.http.HttpServlet• Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable• HttpServlet defines a HTTP protocol specific servlet.• HttpServlet gives a blueprint for Http servlet and makes writing them easier.• HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.
  7. 7. Servlet Life CycleThe Web container manages the life cycle of servlet instances New Destroyed Running init( destroy( ) ) ...( service( ) ) doGet( ) doDelete( ) doPost( doPut( ) )
  8. 8. The init ( ) method• Called by the Web container when the servlet instance is first created• The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed• Override the init() method when: i) You need to create or open any servlet-specific resources that you needfor processing user requests ii)You need to initialize the state of the servlet//A simple servlet lifecycle counter// int count ;public void init(ServletConfig config) throws ServletException { super.init(config); getServletContext().log("init() called"); count=0; }
  9. 9. The service ( ) method• Called by the Web container to process a user request• Dispatches the HTTP requests to doGet(…), doPost(…), etc. depending on the HTTP request method (GET, POST, and so on) – Sends the result as HTTP response• Usually we do not need to override this method protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getServletContext().log("service() called"); count++; response.getWriter().write("Incrementig the count: Count = "+count); }
  10. 10. The destroy() Method• Called by the Web container when the servlet instance is being eliminated ( All threads within the servlets service method have exited (or) Time-out period have passed )• The Servlet specification guarantees that all requests will be completely processed before this method is called• Override the destroy method when: – You need to release any servlet-specific resources that you had opened in the init() method – You need to persist the state of the servlet public void destroy() { getServletContext().log("destroy() called"); }
  11. 11. servletConfig• Object of servletConfig used to pass initialization and context information to servlets• getServletConfig ( ) method allows the servlet to retrieve the object and obtain configuration at anytime• Init () method stores the servletConfig object in a private transient instance variable called config
  12. 12. ServletContext• The javax.servlet.ServletContext interface provides a set of methods that the servlet can use to communicate with the web server.• The ServletContext object is contained within javax.servlet.ServletConfig Object which is provided to the servlet when it is initialized.• Define URI to name mappings• Allow Data to be shared between different servlets• Contains a servlet log• Access to global servlet config and other application servlet context are accessible• It communicates with the server in a non request specific manner
  13. 13. Http Request and Response Structure• HTTP is a stateless protocol.• Server does not have the overhead of tracking client connections.• HTTP transactions are either a request or response.• Servlet can overcome the stateless nature of HTTP by tracking client state using session information stored in URL, hidden fields or cookies.
  14. 14. Http TransactionsA single request or response line – <HTTP Method>/<document address>HTTP/ <Version No> e.g. – GET /index.html HTTP/1.1 – Response line contains an HTTP status code. HTTP/1.1 200 OK Date:……………………….GMT Server: Last-modified: Content-type: text/html Content-length:….bytes
  15. 15. Http Servlet Methods• doGet()• doPost()• doHead()• doDelete()• doOptions()• doPut()• doTrace()• getLastModified()• service()
  16. 16. Http Servlet Request• getMethod() – Returns get/post with which request was made.• getQueryString()• getRemoteUser()• getRequestSessionId()• getSession(boolean) – If FALSE returns current valid session otherwise creates a new session.• isRequestedSessionIdValid()• getCookies()
  17. 17. Http Servlet Response• addCookie(Cookie) – Add cookie to response• encodeUrl(String)• sendRedirect(String)• sendError(int)
  18. 18. Thread Safety• Multithreaded = one servlet, multiple requests simultaneously• Thread safe – not using class variables since one copy of these variables is shared by all threads• Synchronized code blocks , all threads wait until they can enter, one at a time• Servlet 2.4 deprecates SingleThreadModel interface – could not resolve all potential threading issues.

×