j2ee servlets n.
Skip this Video
Loading SlideShow in 5 Seconds..
J2EE Servlets PowerPoint Presentation
Download Presentation
J2EE Servlets

play fullscreen
1 / 23
Download Presentation

J2EE Servlets - PowerPoint PPT Presentation

adem
136 Views
Download Presentation

J2EE Servlets

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. J2EE Servlets

  2. Agenda • Overview • Servlet Interface • Servlet Context • Request • Response • Sample Servlet • Sessions • Dispatching Request • Web Applications • Deployment Descriptor

  3. What is a Sevlet? • Web component managed by servlet container • Generates dynamic content, usually HTML • Small, platform-independent classes compiled to bytecode • Loaded dynamically and run by a container in conjunction with a web server • Interacts with a web client via request - response model based on the the HTTP protocol • Can access databases and other storage systems

  4. What is a Servlet Container? • Execution context of the servlet • Provides network services over which requests and responses are exchanged • Contains and manages servlets through their lifecycle • Can be either built-in into a web server or web enabled application server or installed as an add-on component • Must support the HTTP Protocol (at minimum HTTP/1.0) • May place security restrictions on the environment that a servlet executes in (e.g. Number of simultenously running threads)

  5. Benefits of Servlets • Performance • Scalability • Distributed environment (distributable web applications) • Multithreaded environment • Portability • Platform independence • Ease of development • Part of J2EE (Servlet API is a required API of J2EE) • Standard supported by many vendors and web servers

  6. Typical Scenario • Request is submitted from a web browser • Request is converted to a name-value list by the servlet container • The service() method of a servlet is called with the name-value list together with the response as arguments • The servlet processes the request by invoking EJBs, performing other business logic, connecting to databases or application server extensions • The servlet prepares HTML code to return either directly printing to the response stream

  7. The Servlet Interface void init(ServletConfig config); void service(ServletRequest req, ServletResponse res); void destroy(); ServletConfig getServletConfig(); java.lang.String getServletInfo(); • Central abstraction of the Servlet API • Interface implemented either directly or by extending

  8. Servlet Life Cycle • Loading and instantiating • At start time • Delayed until the service method of the servlet is requested • The servlet container load the servlet class (file system, remote file system, other network services) • The Servlet Container instantiates an object instance • There can be more than one instance (SingleThreadModel) of a given servlet (several servlet definitions which point to the same class) or only one instance (MultipleThreadModel) • Initialization • Point where servlet can read any configuration data, persistent data, make a connection to a database and other costly resources, perform one-time activities • The Servlet Container calls init method of the servlet and passes ServletConfig - access to name-value initialization parameters • On error throw ServletException or UnavailableException

  9. Servlet Life Cycle • End of service • A servlet instance may be kept active in a container for any amount of time • The container allow any threads executing service method to complete • The container executes destroy method - point where a servlet may release any resources and save its state to any persistance storage • No requests can be routed to this instance of the servlet • The instance is released so that it can be garbage collected

  10. Servlet Life Cycle • Request handling • Each request represented by ServletRequest object • Servlet can create the response by using object of type ServletResponse • ServletRequest and ServletResponse are provided as parameters to service • HTTP - HttpServletRequest, HttpServletResponse • Errors during request handling • ServletException • UnavailableException • Permanent - servlet should be removed from the service (destroy is called) • Temporary - SERVICE_UNAVAILABLE (503) is returned with Retry-After header

  11. Multithreading Requests • MultipleThreadModel (default)One instance of a servlet class per servlet definition • SingleThreadModel (marker interface) • Multiple instances of the servlet. Ensures that servlets handle only one request at a time. • No two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet. • The servlet is thread safe. SingleThreadedModel does not prevent synchronization problems that result from servlets accessing shared resources (static class variables, classes outside the scope of the servlet).

  12. The Servlet Context • A servlet's view of the web application within which it is running • One instance per web application (per VM for distributed applications) • The container implements the ServletContext interface • ServletContext • allows a servlet to set and store attributes, log events, obtain URL references to resources • provides a set of methods that a servlet uses to communicate with its servlet container • Context attributes - available to any other servlet of the web application (exits only locally in the VM) • Resources - direct access to static documents (HTML, GIF, JPEG)

  13. The Request • Encapsulates information from the client • HttpServletRequest - HTTP headers and message body • Parameters • getParameter, getParameterNames, getParameterValues • String parameters stored as name-value pairs • Possible multiple parameter values • Attributes • getAttribute, getAttributeNames, getAttributeValues • Objects associated with a request set by the container or a servlet to communicate with another servlet • Single values • Cookies • getCookies

  14. Path Elements & Translation • Request path is composed of • Context Path getContextPath • Servlet Path getServletPath • Following is always true RequestURI = contextPath + servletPath Pattern: /garden Servlet: GardenServlet /catalog/garden/implements -> ContextPath:/catalog ServletPath:/garden

  15. The Response • Encapsulates information to be returned to the client • HttpServletResponse - HTTP headers and message body • Cookies • Helper methods • sendRedirect • sendError • Typical use • Either getOutputStream (binary data) or getWriter (text)

  16. Sample Servlet public class SampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("Hello World!"); out.println("</body></html>"); } }

  17. Sessions • HTTP - stateless protocol • Different requests from the same client should be associated with each other • Strategies for session tracking • Hidden variables • URL rewriting • Cookies • In servlet environment • Session tracking implemented by servlet container • HttpSession provided as an convenient interface • A session persists for a specified period of time

  18. HttpSession • View and manipulate information about a session, such as the session identifier, creation time, last accessed time • Bind objects to sessions, allowing user information to persist across multiple user connections • Session information is scoped only to the current web application (ServletContext) • Binding attributes into a session • getAttribute, setAttribute, removeAttribute • HttpSessionBindingListener - causes an object to be notified when it is bound to or unbound from a session • Session timeouts because there is no explicit client termination

  19. Session Semantics • Multiple servlets may have access to a single session object • Synchronization is the responsibility of a developer • For applications marked as distributable session objects must implement java.io.Serializable interface • Scalability - in distributed environment session objects can be moved from any active node to some other node of the system • All windows of a client are participating in the same session

  20. Dispatching Requests • forward - pass processing to another servlet • Including output of another servlet in the response • RequestDispatcher; can be obtained from ServletContext • include • Can be called at any time • Included servlet cannot set headers or call any method that affects the headers of the response • forward • Can only be called if no output has been commited to a client

  21. Web Applications • Collection of servlets, JSPs, HTML pages and other resources bundled and run on possibly multiple containers • Rooted at a specific path eg. http://www.company.com/catalog • By default one instance must only be run on one VM • Distributable web applications - components distributed across multiple containers • 1:1 mapping between web application and ServletContext • Representation • Structured hierarchy of directories • Archive file

  22. Open Directory Structure • Root directory eg. /catalog • Special WEB-INF directory - not a part of public document tree • Sample directory structure: /index.html /howto.jsp /feedback.jsp /images/logo.gif /WEB-INF/web.xml /WEB-INF/lib/jspbeans.jar /WEB-INF/classes/com/dsrg/servlets/Test.class /WEB-INF/classes/com/dsrg/util/Helper.class

  23. Deployment Descriptor • Elements and configuration information of a web application • Contents of a deployment descriptor • ServletContext init parameters • Session configuration • Servlet/JSP definitions • Servlet/JSP mappings • Mime Type mappings • Welcome file list • Error pages • Security info • XML document