scwcd : servlet web applications : chap : 3

60
1 Servlet Web Applications Helmi ben abdallah @rchitect JEE

Upload: oxia

Post on 19-Jan-2017

202 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: SCWCD : Servlet web applications : CHAP : 3

1

Servlet Web Applications

Helmi ben abdallah @rchitect JEE

Page 2: SCWCD : Servlet web applications : CHAP : 3

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

Page 3: SCWCD : Servlet web applications : CHAP : 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.

Page 4: SCWCD : Servlet web applications : CHAP : 3

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)

Page 5: SCWCD : Servlet web applications : CHAP : 3

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.

Page 6: SCWCD : Servlet web applications : CHAP : 3

6

The ContextThe 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/barIncoming path: /foo/barPath 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.htmlIncoming path: /programs/wordprocessing/wp2.4/start.jsp

Page 7: SCWCD : Servlet web applications : CHAP : 3

7

Extension mapping :The string begins with an asterisk (*).Here is an example of a match:Servlet path pattern:*.jspIncoming path:/catalog/order/start.jspIncoming path:/catalog/form.jspIncoming 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: /sportIncoming path: /sport/index.html

Page 8: SCWCD : Servlet web applications : CHAP : 3

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.

Page 9: SCWCD : Servlet web applications : CHAP : 3

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)

Page 10: SCWCD : Servlet web applications : CHAP : 3

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.

Page 11: SCWCD : Servlet web applications : CHAP : 3

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.

Page 12: SCWCD : Servlet web applications : CHAP : 3

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” “http://java.sun.com/ 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>

Page 13: SCWCD : Servlet web applications : CHAP : 3

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>

Page 14: SCWCD : Servlet web applications : CHAP : 3

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>

Page 15: SCWCD : Servlet web applications : CHAP : 3

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.

Page 16: SCWCD : Servlet web applications : CHAP : 3

16

Basic Servlet Tags<servlet><servlet-name>Search</servlet-name><servlet-class>SearchServlet</servlet-class></servlet>

Page 17: SCWCD : Servlet web applications : CHAP : 3

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.

Page 18: SCWCD : Servlet web applications : CHAP : 3

18

Mapping the URL to the Servlethttp://localhost:8080/features/utilities/SearchFrom this request, we can extract the URI:URI = features/utilities/SearchThe container then uses a default mapping mechanism to find the servlet:/context_name/servlet/Servlet_NameThe 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 wouldlook like the following:c:/projects/birdSite/features/utilities/SearchServlet.class

Page 19: SCWCD : Servlet web applications : CHAP : 3

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 = TurboRacerservlet-name = com.eei.RaceCarServleturl-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.classThe 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).

Page 20: SCWCD : Servlet web applications : CHAP : 3

20

Page 21: SCWCD : Servlet web applications : CHAP : 3

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.

Page 22: SCWCD : Servlet web applications : CHAP : 3

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.

Page 23: SCWCD : Servlet web applications : CHAP : 3

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>

Page 24: SCWCD : Servlet web applications : CHAP : 3

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.

Page 25: SCWCD : Servlet web applications : CHAP : 3

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

Page 26: SCWCD : Servlet web applications : CHAP : 3

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”);…}…

Page 27: SCWCD : Servlet web applications : CHAP : 3

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.

Page 28: SCWCD : Servlet web applications : CHAP : 3

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>

Page 29: SCWCD : Servlet web applications : CHAP : 3

29

• When SpiderInc.com 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.

Page 30: SCWCD : Servlet web applications : CHAP : 3

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.

Page 31: SCWCD : Servlet web applications : CHAP : 3

31

1

Which of the following item(s) can be included in a web application?(Choose all that apply.)A. ServletsB. Utility classesC. Client-side beansD. An image file

Page 32: SCWCD : Servlet web applications : CHAP : 3

32

• A, B, C, D. All the objects defined can be included in a web• application.

Page 33: SCWCD : Servlet web applications : CHAP : 3

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.

Page 34: SCWCD : Servlet web applications : CHAP : 3

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.

Page 35: SCWCD : Servlet web applications : CHAP : 3

35

3

Which of the following files could correctly define an entire web application?A. chat.warB. chat.jarC. chat.xmlD. None of the above

Page 36: SCWCD : Servlet web applications : CHAP : 3

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.

Page 37: SCWCD : Servlet web applications : CHAP : 3

37

4

In which directory are you likely to find the file index.html? (Assume the context is defined as /cars.)A. /carsB. /cars/WEB-INFC. /cars/WEB-INF/resourcesD. /cars/META-INF

Page 38: SCWCD : Servlet web applications : CHAP : 3

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.

Page 39: SCWCD : Servlet web applications : CHAP : 3

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. /orderAppB. /orderApp/WEB-INFC. /orderApp/WEB-INF/libD. /orderApp/WEB-INF/classes

Page 40: SCWCD : Servlet web applications : CHAP : 3

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.

Page 41: SCWCD : Servlet web applications : CHAP : 3

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. /bookB. /book/WEB-INFC. /book/WEB-INF/libD. /book/META-INF

Page 42: SCWCD : Servlet web applications : CHAP : 3

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.

Page 43: SCWCD : Servlet web applications : CHAP : 3

43

7-Given the following data elements, which answer best maps to the servlet?Context path = /bikes/motorsdocbase = c:/projects/bikes/motorsAlias name = R6Servlet name = com.eei.BikeServleturl-pattern = /vehicles/fast/*A. c:/projects/bikes/motors/bikes/motors/vehicles/fast/BikeServlet.classB. c:/bikes/motors/vehicles/fast/com/eei/BikeServlet.classC. c:/projects/bikes/motors/vehicles/fast/R6.classD. c:/projects/bikes/motors/vehicles/fast/com/eei/BikeServlet.class

Page 44: SCWCD : Servlet web applications : CHAP : 3

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.

Page 45: SCWCD : Servlet web applications : CHAP : 3

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

Page 46: SCWCD : Servlet web applications : CHAP : 3

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.

Page 47: SCWCD : Servlet web applications : CHAP : 3

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-mappingB. init-paramC. context-paramD. session-config

Page 48: SCWCD : Servlet web applications : CHAP : 3

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.

Page 49: SCWCD : Servlet web applications : CHAP : 3

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-minB. session-timeout-minC. session-timeout-maxD. session-timeoutE. session-config

Page 50: SCWCD : Servlet web applications : CHAP : 3

50

• D. The session-timeout tag identifies the number of seconds container must wait before removing an inactive HttpSession object.

Page 51: SCWCD : Servlet web applications : CHAP : 3

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

Page 52: SCWCD : Servlet web applications : CHAP : 3

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.

Page 53: SCWCD : Servlet web applications : CHAP : 3

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.

Page 54: SCWCD : Servlet web applications : CHAP : 3

54

• B. When the string passed into the getInitParameter (String• name) method cannot be matched to a param-name tag,

null is• returned.

Page 55: SCWCD : Servlet web applications : CHAP : 3

55

13

• Which opening tag is used to hold content-type mapping information for a response?

A. content-typeB. mapping-typeC. mime-mappingD. content-mapping

Page 56: SCWCD : Servlet web applications : CHAP : 3

56

• C. The mime-mapping tag identifies the MIME type for files with the• specified file extensions.

Page 57: SCWCD : Servlet web applications : CHAP : 3

57

14

In which directory are you likely to find the file myServlet.jar?A. root/WEB-INFB. root/C. root/WEB-INF/libD. root/META-INF/

Page 58: SCWCD : Servlet web applications : CHAP : 3

58

• C. All Java archive files are read from the /lib directory, which is• located inside /WEB-INF.

Page 59: SCWCD : Servlet web applications : CHAP : 3

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.

Page 60: SCWCD : Servlet web applications : CHAP : 3

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).