SCWCD : Servlet web applications : CHAP : 3

Software Craftsman and Computer Science Geek à ITG MANAGEMENT
28 Nov 2015

Contenu connexe


SCWCD : Servlet web applications : CHAP : 3

  1. 1 Servlet Web Applications Helmi ben abdallah @rchitect JEE
  2. 2 THE FOLLOWING SUN CERTIFIED WEB COMPONENT DEVELOPER FOR J2EE PLATFORM EXAM OBJECTIVES COVERED IN THIS CHAPTER: • 2.1 Identify the structure of a web application and web archive file, the name of the WebApp deployment descriptor, and the name of the directories where you place the following: > The WebApp deployment descriptor > The WebApp class files > Any auxiliary JAR files • 2.2 Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: > Servlet instance > Servlet name > Servlet class > Initialization parameters > URL to named servlet mapping
  3. 3 • In this chapter, we will classify the various parts of a web application and identify where these parts must be placed. • The directory layout is the key behind the container’s ability to locate the data it needs.
  4. 4 Understanding a Web Application • It takes many pieces to make a final program that is accessible through the Web. These pieces, when grouped together, are referred to as the web application . A single application can consist of any or all of the following elements: • Servlets • JSP pages • Utility classes • Static documents • Client-side Java applets, beans, and classes • A standard configuration file (required)
  5. 5 Understanding a Directory Structure The hierarchy is made up of three significant layers. 1. The first is the context.It is one or more directories used to locate the web application associated to the client request. 2. Within the context exists the /WEB-INF directory. It contains several subdirectories that help organize class files and compressed Java files. The /WEB-INF directory also contains web.xml. This layer is hidden from the client. the client cannot directly access files from within the /WEB-INF directory. 3. The final layer is quite the opposite. It is located directly within the context and contains all client-viewable files. This includes welcome and error pages, graphic or audio files, and so forth.
  6. 6 The Context The context itself is the root for a single web application. The container then locates the servlet by using the following mapping rules in the order they are performed. Assuming that the “servlet path pattern” defines the request URL and the “incoming path” defines the longest context path match, the servlet container will try to find: Exact mapping : All strings match exactly. Here is an example of a match: Servlet path pattern: /foo/bar Incoming path: /foo/bar Path mapping : The string begins with a forward slash (/) and ends witha forward slash and asterisk (/*). The longest match determines the servlet requested. Here is an example of a match: Servlet path pattern: /programs/wordprocessing/* Incoming path: /programs/wordprocessing/index.html Incoming path: /programs/wordprocessing/wp2.4/start.jsp
  7. 7 Extension mapping :The string begins with an asterisk (*). Here is an example of a match: Servlet path pattern:*.jsp Incoming path:/catalog/order/start.jsp Incoming path:/catalog/form.jsp Incoming path:/test.jsp Default mapping :The container provides server content appropriate for the resource request, such as a default servlet. The string begins with a forward slash (/), and the servlet path is the requested URI minus the context path. The path info is null. Here is an example of a match: Servlet path pattern: /sport Incoming path: /sport/index.html
  8. 8 • Request mapping is case sensitive. • Containers often have implicit mapping mechanisms built into their systems. For example, a container might have *.jsp extensions mapped to enable JSP pages to be executed on demand. The keynote is that explicit mapping by a web application or servlet takes precedence over implicit mapping.
  9. 9 WEB-INF • This directory contains the main files for the application that are not provided to the client by the container. • Through the ServletContext object, which the servlet acquires by using the getServletContext() method, a servlet can access files and code in the /WEB-INF directory by using the following methods: • URL getResource(String path) • InputStream getResourceAsStream(String path)
  10. 10 There are three main categories for content in the /WEB-INF directory: • /WEB-INF/web.xml This contains the deployment descriptor. • /WEB-INF/classes This directory contains all the server- side Java classes, such as servlet and utility classes. • /WEB-INF/lib/*.jar The /lib directory contains all necessary compressed Java files that are used for the web application. These files are referred to as Java archive files or JAR files. They can consist of servlets, JSPs, beans, and utility classes. When loading classes from the /WEB-INF directory, the ClassLoader first loads from the /classes directory and then the /lib directory.
  11. 11 Web Application Archive File (WAR File) You can create a WAR file by using the following command-line statement: jar -cvf ShoppingCart.war * Or you can extract a WAR file by using the following command: jar -xvf ShoppingCart.war The minus sign in front of the options is not mandatory. It is used only as a convention carried forward from Unix. The option tags can be placed in any order.
  12. 12 Listing 3.1: A Sample Deployment Descriptor <?xml version=”1.0” encoding=”ISO-8859-01”?> <!DOCTYPE web-app PUBLIC “-//SUN Microsystems, Inc.// DTD Web Application 2.3//EN” “ dtd/web-app_2_3.dtd”> <web-app> <display-name>Exotic Bird Encyclopedia</display-name> <context path=”/features” docbase=”c:/projects/birdSite/features” reloadable=”true”> <context-param> <param-name>SEARCH_PATH</param-name> <param-value>/features/utilities</param-value> </context-param> </context>
  13. 13 <servlet> <servlet-name>Search</servlet-name> <servlet-class>SearchServlet</servlet-class> <init-param> <param-name>defaultType</param-name> <param-value>cockatiels</param-value> <description>default search value</description> </init-param> </servlet> <servlet-mapping> <servlet-name>Search</servlet-name> <url-pattern>/utilities/*</url-pattern> </servlet-mapping>
  14. 14 <session-config> <session-timeout>60</session-timeout> </session-config> <mime-mapping> <extension>pdf</extension> <mime-type>application/pdf</mime-type> </mime-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
  15. 15 • If you don’t include a context tag, the container assumes a default context of ‘/’. • Within the opening and closing context tags, you can define parameters that are available to all servlets within the web application. • By using the ServletContext method getInitParameter(…), you can pass in the param-name and have the param-value returned within the servlet. • Remember, the value is always represented as a String.
  16. 16 Basic Servlet Tags <servlet> <servlet-name>Search</servlet-name> <servlet-class>SearchServlet</servlet-class> </servlet>
  17. 17 Initialization Parameters <servlet> <servlet-name>Search</servlet-name> <servlet-class>SearchServlet</servlet-class> <init-param> <param-name>defaultType</param-name> <param-value>cockatiels</param-value> <description> default searchvalue </description> </init-param> </servlet> • servlet can contain multiple parameters, they will always be embedded between a set of <init-param></init-param> tags. • the SearchServlet class can use the getInitParameter("defaultType") method, inherited from the GenericServlet class, to get the value cockatiels.
  18. 18 Mapping the URL to the Servlet http://localhost:8080/features/utilities/Search From this request, we can extract the URI: URI = features/utilities/Search The container then uses a default mapping mechanism to find the servlet: /context_name/servlet/Servlet_Name The container looks for the context directory /features and finds that it is located in c:/projects/birdSite/features. The servlet is then mapped to the url-pattern directory /utilities, and the alias name Search is then mapped to a class file called SearchServlet. The complete location would look like the following: c:/projects/birdSite/features/utilities/SearchServlet.class
  19. 19 Based on the information provided,you, like the container, should be able to construct the full path for the servlet. context path = /car/engines docbase= c:/projects/ alias name = TurboRacer servlet-name = com.eei.RaceCarServlet url-pattern = /vehicles/fast/* By utilizing all the information, you should map the servlet to the following location: c:/projects/car/engines/vehicles/fast/com/eei/RaceCarServlet.class The container takes the url-pattern (/vehicles/fast) that is associated to the servlet alias name (TurboRacer) and then maps that name to the actual servlet class (com.eei.RaceCarServlet).
  20. 20
  21. 21 Session Configuration • If portions of those users are inactive, then the application is wasting memory resources. A timeout flag can be set two ways: 1. Within the servlet code, by using the HttpSession object’s method,setMaxInactiveInterval(int) 2. Within the web.xml file by using the session-config tag.
  22. 22 The first approach utilizes servlet code to set the maximum number of seconds a request can remain inactive. The following code snippet demonstrates how this can be done: … public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { … HttpSession session = req.getSession(); session.setMaxInactiveInterval(60); … } … The downside to this approach is that when the number of seconds needs to be modified, the code itself must be recompiled.
  23. 23 Why not use the second approach altogether because it uses the deployment descriptor to define the value and exclude the code from the servlet?” • A developer might opt to choose one approach over the other because the first applies the timeout value to a specific servlet, rather than the entire web application. • The second approach defines the maximum time all inactive HttpSession objects can exist through the web.xml file by using the session-config tag. > <session-config> > <session-timeout>60</session-timeout> > </session-config>
  24. 24 MIME Type Mappings • When transmitting information between the client and server, both parties need to know the format of the content being transferred. • The Multipurpose Internet Mail Extensions (MIME) type defines the format of the request or response. • A MIME type is a String that defines the type and subtype: type/subtype. Some common examples are text/html, text/plain,and image/gif.
  25. 25 • When a servlet sends a response to a client, the browser needs to know how to render the information received. Consequently, the server can construct a response to notify the client of the MIME type, by using two different approaches: 1. By using the HttpServletResponse’s method: setContentType(…) 2. By using the mime-mapping tag in the web.xml file for the web application
  26. 26 The first approach utilizes servlet code to set the MIME type of the response. The following code snippet demonstrates how this can be done: … public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { … res.setContentType(“application/pdf”); … } …
  27. 27 • To apply the content type to all public files of a specific extension within an entire web application, you can use the mime-mapping tag. The following example demonstrates how the context will automatically associate the application/pdf MIME type with all files with the extension of .pdf: <mime-mapping> <extension>pdf</extension> <mime-type>application/pdf</mime-type> </mime-mapping> • After the client receives this response, it knows it must use a tool such as Adobe Acrobat Reader to interpret the .pdf response.
  28. 28 Welcome File List • The index.html file is the default welcome page for servlets. Including the welcome-file-list tag in the web.xml file overrides the server defaults and enables the container to search for specified welcome pages. • A welcome list can point the web server to alternative display pages. <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>start.html</welcome-file> <welcome-file>go.html</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list>
  29. 29 • When is accessed, the welcome page index.html is displayed by default. Now, when the employees/ link is accessed, the user might be prompted for a login and password entry. • After access is granted, then a welcome page could be generated dynamically to acknowledge the user’s name and information. • The welcome page for the employee site is called index.jsp. In order for the container to associate the index.jsp file to the welcome page, the file index.jsp must be defined in the web.xml file with a welcome-file tag. • This entry identifies additional filenames for the container to look for when searching for the welcome page for a site. In our example, the container will first look for index.html.
  30. 30 • In our example, the container will first look for index.html. • If it can find it in the employees/ directory, it will look at the first filename in the welcome-file list and search for that file next. • Because index.jsp is found, the container displays that page to the client. Without the XML entry, the container would fail to display the starting page because index.html is not available.
  31. 31 1 Which of the following item(s) can be included in a web application?(Choose all that apply.) A. Servlets B. Utility classes C. Client-side beans D. An image file
  32. 32 • A, B, C, D. All the objects defined can be included in a web • application.
  33. 33 2-Which of the following statements is true? A. It is mandatory that all servlet-compliant containers adhere to the structured directory hierarchy defined by the servlet specification. B. It is not mandatory or required that all servlet containers adhere to the directory structure defined by the specification. C. In order for a servlet container to be certified by Sun, it does not need to adhere to the specification. D. None of the above.
  34. 34 • B. Although it is recommended, it is not mandatory or required that • all servlet containers adhere to the directory structure defined by the • spec. However, to be Sun certified, a servlet container must meet • the requirements of the specification.
  35. 35 3 Which of the following files could correctly define an entire web application? A. chat.war B. chat.jar C. chat.xml D. None of the above
  36. 36 • A. Although a JAR file contains compressed classes and resources for • a Java application, a WAR file specifically contains these same types • of files, but for a web application.
  37. 37 4 In which directory are you likely to find the file index.html? (Assume the context is defined as /cars.) A. /cars B. /cars/WEB-INF C. /cars/WEB-INF/resources D. /cars/META-INF
  38. 38 • A. The index.html file is forwarded to the web client. As a result, it cannot be located in either the /WEB-INF or /META-INF directories, or any of their subdirectories.
  39. 39 5 Assume the context for the web application you are working with is /orderApp. In which directory are you most likely to find the single file Order.class? A. /orderApp B. /orderApp/WEB-INF C. /orderApp/WEB-INF/lib D. /orderApp/WEB-INF/classes
  40. 40 • D. All individual classes are located in the /WEB- INF/classes directory. • If the class is compressed and converted to a JAR file, its JAR file • needs • to be placed in the /WEB-INF/lib • directory.
  41. 41 6 Assume the context for the web application you are working with is /book. In which directory are you most likely to find the file called BookApp.war? A. /book B. /book/WEB-INF C. /book/WEB-INF/lib D. /book/META-INF
  42. 42 • A. The WAR file is usually stored in the context directory. Within the file exists the /WEB-INF directory and all its subdirectories. The • /META-INF directory must exist within the WAR file as well.
  43. 43 7-Given the following data elements, which answer best maps t the servlet? Context path = /bikes/motors docbase = c:/projects/bikes/motors Alias name = R6 Servlet name = com.eei.BikeServlet url-pattern = /vehicles/fast/* A. c:/projects/bikes/motors/bikes/motors/vehicles/fast/ BikeServlet.class B. c:/bikes/motors/vehicles/fast/com/eei/BikeServlet.class C. c:/projects/bikes/motors/vehicles/fast/R6.class D. c:/projects/bikes/motors/vehicles/fast/com/eei/
  44. 44 • D. The docbase identifies the actual directory starting path for the • servlet. It includes the context path, so there is no need to repeat • the path directory structure. The url-pattern then defines the specific • location of each servlet rather than storing them all at the root. Finally, • the package structure information is incorporated into the path to • locate the end class.
  45. 45 8-The <session-timeout></session-timeout> tag must be embedded in which outer tags? A. <web-app><session-config>HERE</session-config> </web-app> B. <web-app><servlet><servlet- config>HERE</servletconfig></servlet></web-app> C. <web-app>HERE</web-app> D. None of the above
  46. 46 • A. The session-timeout tag is used in conjunction with the • session-config tag. It is not specific to a servlet, but rather applies • to all servlets in the defined web application.
  47. 47 9 Which of the following XML tags apply features to the entire web application, rather than to an individual servlet? (Choose all that apply.) A. mime-mapping B. init-param C. context-param D. session-config
  48. 48 • A, C, D. The mime-mapping tag applies the MIME type for any file with the specified file extensions. The init-param is not a correct answer because it provides parameters for a specific servlet, unlike the context-param tag. This tag is general to all files in the web application. Finally, the last option is also correct because the timeout amount defined with the session-config • tag applies to all HttpSession objects.
  49. 49 10-Which of the following tags is used to identify the minimum amount of time a container must wait to remove an inactive HttpSession object? A. session-config-min B. session-timeout-min C. session-timeout-max D. session-timeout E. session-config
  50. 50 • D. The session-timeout tag identifies the number of seconds container must wait before removing an inactive HttpSession object.
  51. 51 11-Which of the following methods is used to retrieve the value associated to the parameter name provided within the init-param tag? A. getParameter(String name) B. getInitParameter(String name) C. getParameters() D. None of the above
  52. 52 • A. The getParameter(String name) of the ServletRequest • class is used to retrieve the value associated to the name passed in for a specific servlet. This should not be confused with the getInitParameter(String name) method found in the ServletContext class and used to retrieve context parameters.
  53. 53 12 • What is the return value of a method call to getInitParameter (String name) if the name passed in is not found in the web.xml document? A. A ServletException is thrown. B. null is returned. C. A blank string is returned. D. The code will not compile.
  54. 54 • B. When the string passed into the getInitParameter (String • name) method cannot be matched to a param-name tag, null is • returned.
  55. 55 13 • Which opening tag is used to hold content-type mapping information for a response? A. content-type B. mapping-type C. mime-mapping D. content-mapping
  56. 56 • C. The mime-mapping tag identifies the MIME type for files with the • specified file extensions.
  57. 57 14 In which directory are you likely to find the file myServlet.jar? A. root/WEB-INF B. root/ C. root/WEB-INF/lib D. root/META-INF/
  58. 58 • C. All Java archive files are read from the /lib directory, which is • located inside /WEB-INF.
  59. 59 15-Which of the following statements is true? A. Request mapping is case sensitive. B. If mapping information is not included, the container will look to default directories defined by the server’s deployment descriptor to find the specified servlet. C. Containers often have implicit mapping mechanisms built into their systems. D. All of the above.
  60. 60 • D. When matching URL names to their respective files or directories, the casing is important. This is best explained when trying to match Java files. A servlet called MyServlet.class is different from onecalled Myservlet.class. The next two options are true as well,because containers resort to default mapping techniques and are often built with implicit mapping mechanisms (as defined by the specification).