SCWCD : The servlet container : CHAP : 4

Software Craftsman and Computer Science Geek
28 de Nov de 2015

Más contenido relacionado


SCWCD : The servlet container : CHAP : 4

  1. 1 The Servlet Container Model Helmi ben abdallah @rchitect JEE
  2. 2 THE FOLLOWING SUN CERTIFIED WEB COMPONENT DEVELOPER FOR J2EE PLATFORM EXAM OBJECTIVES COVERED IN THIS CHAPTER: 3.1 Identify the uses for and the interfaces (or classes) and methods to achieve the following features: Servlet context init. Parameters Servlet context listener Servlet context attribute listener Session attribute listeners 3.2 Identify the WebApp deployment descriptor element name that declares the following features: Servlet context init. Parameters Servlet context listener Servlet context attribute listener Session attribute listeners
  3. 3 3.3 Distinguish the behavior of the following in a distributable: Servlet context init. Parameters Servlet context listener Servlet context attribute listener Session attribute listeners
  4. 4 ServletContext • In this section, we will first discuss the details and methods associated with a ServletContext object. This includes how any servlet within an application can use its context to access the following: • Initialization parameters passed through web.xml • An InputStream to read data from a specified resource • A RequestDispatcher object to transfer a request and response object • Attributes shared by all resources After you understand the value that a ServletContext adds to an application, we will shift gears and cover the various listener interfaces and event classes that can be used to respond to changes in a context’s life cycle and attributes. The two interfaces we will discuss are: • ServletContextListener • ServletContextAttributeListener • The ServletContext is a critical object that helps glue all the pieces of an application together.
  5. 5 ServletContext Methods and Attributes • For each web application, there exists one ServletContext object contained within the application’s ServletConfig object. • The context object acts as a reference to the web application. When a servlet is initialized, the container provides it a handle to the context object for the servlet to communicate with the container. • All servlets within the application use the single context object to access information about the container and server in which they reside. • This information can then be displayed to the client and/or used to change or restrict servlet behaviors.
  6. 6 For example, the context can be used to dispatch a request, write to a log file, or simply learn about the servlet version being supported. • The context can be accessed by the servlet directly or indirectly. Because all servlets extend an implementation of the GenericServlet class, they have direct access to the following method: • ServletContext getServletContext() This method returns the single context object associated with the entire web application. This method is originally defined in the ServletConfig interface, which the GenericServlet class implements.
  7. 7
  8. 8
  9. 9 Parameter values usually define the application’s configuration information at deployment time. The value associated with the name is represented as a String . however, it can be converted to an appropriate object under the correct circumstances. For example, a parameter might provide a hidden file or image path and name that servlets might be interested in loading at some point, or it might simply provide an e-mail address to the application’s webmaster. By using the context-param tag within the DTD, you can specify the name and value pair, as seen here: <context-param> <param-name>picture</param-name> <param-value>/WEB-INF/graphics/image.gif</param-value> </context-param> The context-param tag must be placed at the start of the web-app tag. In other words, it can follow the <web-app> tag or its <description></description> tag only.
  10. 10 • All servlets within the web application can access this filename by using the following methods available in the ServletContext class: • String getInitParameter( String name ) :By passing in the name of the parameter, this method returns a string representation of the value. A null value is returned if the parameter doesn’t exist. • Enumeration getInitParameterNames() : This method returns an enumeration of all names defined within the context-param tags. If there are none, the return value is empty.
  11. 11 URL getResource(String path) : This method returns a local or remote resource to the specified path. The path is viewed as relative to the context for the application and begins with a forward slash (/). If a resource cannot be mapped to the specified path, the method returns a null. InputStream getResourceAsStream(String path) This method creates an InputStream linked to a resource for the path parameter. The path variable can consist of a resource of any type or length. String getMimeType(String file) This method returns a string representation of the MIME type for the specified file. RequestDispatcher getRequestDispatcher(String path) This method returns the RequestDispatcher object to the resource specified by the path. It enables a current servlet to forward a request to the resource or to include the resource in a response.
  12. 12 Continuing our picture example, we are going to read in the image file to convert it to an ImageIcon object that we can use in an applet embedded within the client interface: public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { ServletContext context = getServletContext(); String pictureName = context.getInitParameter(“picture”); InputStream is = context.getResourceAsStream(pictureName); byte[] array = new byte[1024];; ImageIcon icon = new ImageIcon(array); is.close(); }
  13. 13 • Aside from providing read-only access to initialization parameters, the context also enables the servlet to read from and write to context attributes. • Unlike parameters, attributes allow the passing of Objects rather than just Strings. Attributes are used to share common objects with various resources. • Specifically attributes are a way for the server to communicate information to the servlet. • The server could make available statistics on the server load,or pass a handle to a shared resource pool, or provide other bits of information available at the server level. • The only mandatory attribute a server must make available is the location of a private directory for the application’s context. • This value can be accessed through the javax.servlet.context.tempdir attribute. Needless to say, attributes can also be set by the user.
  14. 14 Attributes are defined and stored by using getXXX and setXXX methods. Unlike parameters, they are not defined within a deployment descriptor. • void setAttribute(String name, Object value) This method binds the specified object to the name for access by all resources within the web application. • Object getAttribute(String name) This method returns the bound object to the name specified.
  15. 15 A servlet uses the getAttribute() method to retrieve the stored attribute values. For example, you can now construct the part of the servlet that displays the menu with the defined daily special:
  16. 16 lists the predefined attribute names that are most likely used to set general messaging and exceptions for a ServletContext object.
  17. 17 The following are a few that you should be aware of: • Parameters can be set only from within the container or the web.xml file. Attributes, however, can be set by the servlet or the container. • Parameters return only Strings, whereas attributes allow key names to be associated with Objects. • The lookup names used for attributes are either predefined or custom, but they should be defined by using a package structure. For example, the attribute name for error messages is javax.servlet.error .message.
  18. 18 Listener Interfaces and Event Classes
  19. 19 ServletContextListener • A class that implements the ServletContextListener interface must define two methods: • void contextInitialized(ServletContextEvent e) This method is called when the context is created. You are guaranteed that this method will complete before any requests are serviced. • void contextDestroyed(ServletContextEvent e) This method is called when the context is about to be destroyed. This method acts like a finalize method. It is used to clean up resources.
  20. 20
  21. 21
  22. 22
  23. 23 Here is a code snippet showing how a servlet could use the attributes to accomplish database tasks: public class QueryServlet extends HttpServlet { public void doGet(HttpRequestServlet req,HttpResponseServlet res) throws IOException, ServletException { … SerlvetContext context = getServletContext(); PooledConnection con = (PooledConnection)context.getAttribute(“con”); Connection connection = con.getConnection(); Statement stmt = connection.createStatement(); …}} ConnectionPoolHandler is defined within the web.xml file: <listener> <listener-class> com.spiderInc.ConnectionPoolHandler </listener-class> <listener>
  24. 24 • The servlet 2.3 specification mandates that the container complete instantiations of the listener classes in the application prior to executing the first request for the application. • As a result, these tags should appear before the servlets are declared in the DTD file. All event listener classes use the same listener tag. There is no need to make a method call such as addXXXListener. By using reflection, the server handles the registration between it and the listener. It is mandatory that the web container create an instance of all listener classes and register them for event notification before the first request for the application is processed. Also, the container must maintain a handle to the listener until the last request is made for the application.
  25. 25 ServletContextEvent • When the container creates or destroys a context, it generates a ServletContextEvent object that contains a reference to the actual ServletContext. • An event is simply an object that holds data about an activity that took place. • Usually, it has only get methods to access information about the object. For the ServletContextEvent class, the following method is available: • ServletContext getServletContext() This method returns a handle to the application’s ServletContext.
  26. 26 ServletContextAttributeListener • To ensure application-wide consistency, receiving notification of any changes to the attributes would be beneficial. The ServletContextAttributeListener provides the solution. An implementing class must define the following methods: • void attributeAdded(ServletContextAttributeEvent e) This method is called when an attribute is added to the context. • void attributeRemoved(ServletContextAttributeEvent e) This method is called when an attribute is removed from the context. • void attributeReplaced(ServletContextAttributeEvent e) This method is called when an existing attribute value is changed. For example, a servlet might change the context database attribute. The ServletContext AttributeListener’s attributeReplaced(…) method would be called.The listener could then disconnect from the old database, get the new value, and reconnect to the new database.
  27. 27 ServletContextAttributeEvent • The ServletContextAttributeEvent class extends the ServletContextEvent class and adds two methods to acquire the name and value of the attribute. • In addition to the getServletContext() method, the following methods are available: • String getName() This method returns the name of the attribute being created, replaced, or removed. • Object getValue() This method returns the object of the attribute being created, replaced, or removed.
  28. 28 HttpSession • While the context provides servlets access to the container’s data, a • An application is made up of many pieces. A significant piece is a session object. An HttpSession object is created when a user sends its first request to an application. • The object is maintained on the server end and can be configured to track each action the user takes while at the site. Remember,with HTTP, each request/response transaction creates a new object. • During the life of the session, the user is likely to make multiple requests while transferring information to the server. The user information can be stored in the session to eliminate the need to resend the information to the server.
  29. 29 A shopping cart provides the perfect example of how sessions work.
  30. 30 • The session information is used to verify the order before the information is written to a database. • When the user is finished, all necessary data can be written to the appropriate storage locations and the session is removed. • The HttpSession object does not automatically track user actions. • Capturing and storing the information is the responsibility of the developer.
  31. 31 • it can use the HttpServletRequest class to access the current session or create a new one: • HttpSession getSession(boolean value) :This method gets the current session for the request user. A true parameter creates a new session object if one does not already exist. • After a servlet has a handle to the session object, it can use the methods within the HttpSession class to manipulate the session’s data. Some of those methods are as follows: • Object getAttribute(String name) This method returns the object associated with the specified name. For example, a session can hold objects, such as a bean, for the user. • void setAttribute(String name, Object value) This binds an attribute object to a key name. • void removeAttribute(String name) This removes the bound object and name from the session based on the specified name.
  32. 32 HttpSessionListener • HttpSessionListeners are notified when a session is created or destroyed. • Let’s say you have a brokerage application that closely monitors the user’s every action to validate the purchase or sale of stocks. To prevent any customer disputes, the brokerage writes each action to a hard disk while the customer is logged in. • As soon as a session becomes active, you want to make a new and unique file for that customer. Your listener could perform the necessary steps when it receives notification that a new session has been added to the server. • These are the methods that an implementing class must define: • void sessionCreated(HttpSessionEvent e) This method is called when a session is created. • void sessionDestroyed(HttpSessionEvent e) This method is called to identify that a session has been invalidated.
  33. 33
  34. 34 • In the previous code example, it’s important to note that we use the session.getId() method to create a file object. This approach guarantees the creation of a unique file for each session based on the session name. • Basically, no two sessions can overwrite each other. The servlet can use the HttpServletRequest object to get the session and access the file.
  35. 35 • After the servlet accesses the session object, it can get the file attribute. • It wraps the File object in a FileWriter and filters through the request data to then write it to the file. • When the session is invalidated, the HttpSessionListener is notified and the sessionDestroyed(…) method is called to then write the file to a database.
  36. 36 HttpSessionEvent • When a session is created or destroyed, an HttpSessionEvent object is instantiated to store a handle to the actual session: • HttpSession getSession() This method returns the HttpSession object. • Because multiple clients can access a site at one time, the listener will be called each time a new session is created. The getSession() method returns the session for the session object created or destroyed.
  37. 37 HttpSessionAttributeListener • In an effort to monitor the client’s actions, you can utilize the HttpSessionAttributeListener interface to receive notification when a client session’s attributes are changed. • void attributeAdded(HttpSessionBindingEvent e) This method is called after an attribute is added to a session. • void attributeRemoved(HttpSessionBindingEvent e) This method is called after an attribute is removed from a session. • void attributeReplaced(HttpSessionBindingEvent e) This method is called after an attribute is replaced within a session.
  38. 38 Attribute changes to a ServletContext or an HttpSession object can occur concurrently. Because containers are not required to synchronize the listener notifications, it is possible to have one notification corrupt the data of another. Consequently, the developer must maintain the integrity of the attribute values when coding the listener classes.
  39. 39
  40. 40 HttpSessionBindingEvent • When an action takes place with respect to a session’s attributes, an HttpSessionBindingEvent object is created. The HttpSessionBindingEvent class extends the HttpSessionEvent class and adds methods to access attribute information. This object stores a handle to the session, the attribute name, and attribute value. The methods are as follows: • HttpSession getSession() This method returns a handle to the session object. • String getName() This method returns the name bound or unbound to the session. • Object getValue() This method returns the value that has been added, removed, replaced, not bound, or unbound from the session. The event is either passed to an HttpSessionAttributeListener or HttpSessionBindingListener.
  41. 41 HttpSessionActivationListener • The HttpSessionActivationListener is used to maintain sessions that migrate from one server to another. When a session is about to be moved to a new server, it is passivated, or made inactive. After the session is on the new server, it is brought back to life and activated. • Th e implementing interface is notified during both these events. This provides an opportunity to save or store data across Java Virtual Machines (JVMs). • A listener must implement the following methods: • void sessionDidActivate(HttpSessionEvent se) This method is called right after the session is activated. At this point, the session is not yet in service. • void sessionWillPassivate(HttpSessionEvent se) This method is called when a session is about to be passivated. At this point, the session is no longer in service.
  42. 42
  43. 43 HttpSessionBindingListener • When a session attribute is added, removed, or replaced, the HttpSession AttributeListener is notified. The HttpSessionBindingListener is very similar in that it is notified when an object is bound or unbound to a session. • The difference between the two listeners is based on whether you would like to handle the event change from the session’s perspective or from the object’s perspective: • The HttpSessionAttributeListener looks at all objects added to the session. It manages all attribute changes for the session. • The HttpSessionBindingListener lets the object know when it is bound (added) or unbound (removed) from the session so it can directly respond to the event. When a session times out or is invalidated, objects are unbound from the session. HttpSessionBindingListener is notified and HttpSessionAttribute Listener is not.
  44. 44 The implementing class must define the following methods: • void valueBound(HttpSessionBindingEvent event) This method identifies the session and notifies the object that it is being bound to a session. • void valueUnbound(HttpSessionBindingEvent event) This method identifies the session and notifies the object that it is being unbound from a session.
  45. 45 • In general, event listener classes are used to respond to changes made to the servlet context and HTTP sessions. They are instantiated and registered in the web container when the application is being deployed. • An application can have multiple listeners for each event type and the order of invocation can be specified within the container. • When the application is shut down, the container will first invalidate a session and invoke session listeners and then invoke context listeners to close the application.
  46. 46 Filters • In photography, a single image can be changed greatly by the filter used to capture the picture. • One filter might soften edges, while another might enhance the color contrast by hardening edges. • Another might add the date and author signature to the photo. These alterations do not change the fundamental image; instead, they provide subtle enhancements. • A filter is often a thin layer of some sort that provides subtle changes to a particular object.
  47. 47 • In the Java world, a filter can be applied to one or more servlets/JSPs or application files. Imagine that a client selects an image in JPEG format and sends it to a servlet to modify. If the servlet can handle only TIF files, a filter can be used to handle the conversion before the servlet even accesses the image. • Another example of filter use is to compress the response output stream to improve bandwidth utilization. • The filter could use the request headers to check whether the client (browser) supports compression, and if,so, wrap the response object with a custom writer or output stream object that handles compression. The stream would then eliminate unnecessary bits and transfer content at a faster rate. Filters can be used to encrypt or decrypt data, to log and audit activity, and to trigger events. The options are endless.
  48. 48 The Life Cycle • A filter is an object that can transform a request or modify a response. • It can preprocess a request before it reaches a servlet and it can postprocess a response after it leaves a servlet. Figure 4.4 displays how the filter intercepts the request and response objects.
  49. 49
  50. 50 The Filter • Filters are quite easy to create. The difficulty lies in the logic used to manipulate the content. To create a filter, you must follow three simple steps. • The filter class must: 1.Implement the appropriate interface 2.Define its methods 3.Be declared within the deployment descriptor
  51. 51 Creating the Filter • All filters must implement the javax.servlet.Filter interface. This interface defines three abstract methods that are called during different points of the filter’s life cycle. They include: • public void init( FilterConfig config ) • public void doFilter(ServletRequest req, ServletResponseresp, FilterChain chain) • public void destroy()
  52. 52 • When a filter is activated, the first method that is called is • Init(FilterConfig config) • . This method is used to prepare or initialize the filter for service. The method is passed a javax.servlet.FilterConfig object, which contains deployment descriptor information and a handle to the application’s context. • This object can be used to: > Retrieve the filter name defined within the deployment descriptor. > Retrieve the initialization parameters defined within the deployment descriptor. > Return a reference to the ServletContext object associated with the request or response.
  53. 53 • After the init(…) method completes, the doFilter( ServletRequest req,ServletResponse resp,FilterChain chain )method is called next. This method represents the body of the filter. It handles any conversions, processing, or alterations that must be done before the request object is accessed by the servlet or after the response object is sent from the servlet. To accomplish its task, the filter can use the ServletRequest object to invoke methods such as setAttribute(…) to change the request characteristics. Header data can also be accessed or changed by casting the request to an HttpServletRequest. • A filter should be written to accomplish a particular task related to the request or response. It should not be written to accomplish many tasks.
  54. 54 • Instead, multiple filters should be created to tackle each task, and then they should be chained. Chaining filters means one filter calls the next. • The process is managed by using the FilterChain handle passed to the Filter object’s doFilter(…) method. • A FilterChain is an object provide by the servlet container. Its purpose is to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource (for example, the client or servlet) at the end of the chain. Access to this object enables one filter to be chained to another. The interface has one method: • doFilter( ServletRequest req, ServletResponse resp ) • . If the filter uses another filter, the current filter can call chain .doFilter(req, resp) , passing the current request and response object to the next. • The last method called is destroy() • . This method is called by the web container to indicate that the filter will be removed from service. If the filter uses other resources, you might want to deallocate memory to prepare the filter object for garbage collection.
  55. 55
  56. 56 Defining the Deployment Descriptor The first approach links the filter to a single servlet (assuming you are using this filter on an actual servlet) by using the servlet-name tag This enables the developer to apply the filter to a group of servlets, JSPs, or any static content. Using the url-pattern tag, you can identify the files or types of files to which the filter is to be applied. The filter and filter-mapping tags must be defined before any servlet tags. Listener tags are defined in this same region.
  57. 57