The root element of the file is: 'web-app' XML file is case sensitive, therefore, web-app and WEB-APP are invalid, web-app must be in lower case.
XML elements are not only case sensitive, but also appear in other elementsOrderSensitive.
In web-app elements, the order of elements is also important. Servers do not necessarily require this order, but they allow (in fact some servers do this) to completely reject the execution of Web applications that contain elements with incorrect order. This indicates that the Web. xml file with non-standard element order cannot be transplanted.
The following list shows the order of all valid elements that can directly appear in the Web-app element.
The icon element indicates the location of one or two image files of a Web application using IDE and GUI tools.
L display-name element provides a GUI tool that may be used to mark the name of a specific web application.
L The description Description element provides descriptive text related to this.
L The context-Param element declares the initialization parameters within the application range.
L The filter element associates a name with a class that implements the javax. servlet. Filter interface.
L once a filter-mapping is named, the filter-mapping element should be used to associate it with one or more servlet or JSP pages.
L added event listening in listener servlet API Version 2.3. Program The event listener is notified when a session or servlet environment is created, modified, or deleted. The listener element specifies the event listener class.
L servlet must first name the servlet or JSP page when setting initialization parameters or custom URLs to the servlet or JSP page. The servlet element is used to complete this task.
L The servlet-mapping server generally provides the servlet with a default URL: http: // host/webappprefix/servlet/servletname. However, this URL is often changed so that the servlet can access initialization parameters or process relative URLs more easily. When you change the default URL, use the servlet-mapping element.
L session-config if a session is not accessed for a certain period of time, the server can discard it to save memory. You can use the setmaxinactiveinterval method of httpsession to explicitly set the timeout value for a single session object, or use the session-config element to specify the default timeout value.
L mime-mapping the mime-mapping element provides this guarantee if the web application wants to assign specific MIME types to special files.
L The Welcom-file-list welcome-file-list element indicates which file the server uses when it receives a URL that references a directory name rather than a file name.
L The error-page element enables the returned HTTP status Code When a specific type of exception is thrown, you can specify the page to be displayed.
L The taglib element specifies an alias for the tag library descriptor file (TAG libraryu descriptor file. This feature allows you to change the location of TLD files without editing the JSP pages that use these files.
L The resource-env-ref element declares a resource-related management object.
L The resource-ref element declares the external resources used by a resource factory.
L The Security-constraint security-constraint element specifies the URL to be protected. It is used together with the login-config element.
L login-config uses the login-config element to specify how the server grants permissions to users attempting to access protected pages. It is used with the sercurity-constraint element.
L The Security-role security-role element provides a list of security roles that appear in the role-name sub-element of the security-role-ref element in the servlet element. Declaring roles separately makes it easier for advanced ide to process security information.
L The env-entry element declares the environment items of the Web application.
L The EJB-ref element declares a reference to the main directory of an EJB.
L The EJB-local-ref element declares the application of the local main directory of an EJB.
3. Name allocation and customized ul
One of the most common tasks completed in Web. XML is to give the servlet or JSP page names and custom URLs. Use the servlet element to assign a name, and use the servlet-mapping element to associate the custom URL with the name you just allocated.
3.1 allocation name
To provide initialization parameters, define a custom URL for the servlet or JSP page or assign a security role, you must first give the servlet or JSP page a name. You can assign a name through the servlet element. The most common formats include servlet-Name and servlet-class sub-elements (in the Web-app element), as shown below:
XML Code
<Servlet>
<Servlet-Name> test </servlet-Name>
<Servlet-class> moreservlets. testservlet </servlet-class>
</Servlet>
3.2 define custom URLs
Most servers have a default Serlvet URL:
Http: // host/webappprefix/servlet/packagename. servletname. Although it is convenient to use this URL during development, we often want another URL for deployment. For example, you may need a URL (such as http: // host/webappprefix/anyname) at the top layer of the Web application, and there is no servlet entry in the URL. The URL at the top layer simplifies the use of relative URLs. In addition, for many developers, the top-level URL seems to be shorter than the longer and more troublesome default URL.
In fact, you sometimes need to use custom URLs. For example, you may want to disable the default URL ing to better enforce security restrictions or prevent users from accidentally accessing servlets without initialization parameters. If you disable the default URL, how do you access the servlet? In this case, only custom URLs are used.
To assign a custom URL, you can use the servlet-mapping Element and Its servlet-Name and URL-pattern sub-elements. The servlet-name element provides an arbitrary name that can be used to reference the servlet. url-pattern describes the URL relative to the root directory of the Web application. The value of the URL-pattern element must start with a slash.
Below is a simple web. xml excerpt, which allows the use of URL http: // host/webappprefix/urltest instead of http: // host/webappprefix/servlet/test or
Http: // host/webappprefix/servlet/moreservlets. testservlet. Note that the xml header, doctype declaration, and web-app blocking elements are still required. In addition, we can recall that the order in which XML elements appear is not random. In particular, you need to put all servlet elements before all servlet-mapping elements.
XML Code
<Servlet>
<Servlet-Name> test </servlet-Name>
<Servlet-class> moreservlets. testservlet </servlet-class>
</Servlet>
<! --... -->
<Servlet-mapping>
<Servlet-Name> test </servlet-Name>
<URL-pattern>/urltest </url-pattern>
</Servlet-mapping>
The URL mode can also contain wildcards. For example, the following applet instructs the server to send all requests starting with the URL prefix of the Web application and ending with. asp to the servlet named bashms.
XML Code
<Servlet>
<Servlet-Name> bashms </servlet-Name>
<Servlet-class> msutils. asptranslator </servlet-class>
</Servlet>
<! --... -->
<Servlet-mapping>
<Servlet-Name> bashms </servlet-Name>
<URL-pattern>/*. asp </url-pattern>
</Servlet-mapping>
3.3 naming JSP page
Because JSP pages need to be converted to sevlet, we naturally want to name JSP pages just like servlet. After all, JSP pages may benefit from initialization parameters, security settings, or custom URLs, just like Serlvet. Although the JSP page background is actually a servlet sentence, there is a key suspicion, you do not know the actual class name of the JSP page (because the system selects this name ). Therefore, to name a JSP page, you can replace the JSP-file element with the servlet-calss element, as shown below:
XML Code
<Servlet>
<Servlet-Name> test </servlet-Name>
<JSP-File>/testpage. jsp </JSP-File>
</Servlet>
<Servlet>
<Servlet-Name> test </servlet-Name>
<JSP-File>/testpage. jsp </JSP-File>
</Servlet>
The reason for naming the JSP page is exactly the same as that for naming the servlet: to provide a name that is used together with custom settings (such as initialization parameters and security settings), and, to change the URL of the activated JSP page (for example, so that multiple URLs can be processed through the same page, or remove from the URL. JSP extension ). However, when setting initialization parameters, you should note that the JSP page uses the jspinit method instead of the init method to read the initialization parameters.
For example, a simple JSP page named testpage. jsp is provided in listing 5-3. It only prints the local part of the URL used to activate it. Testpage. jsp is placed on the top layer of the deploydemo application. In program list 5-4, a Registration Name pagename is assigned, and the registration name is associated with a URL in the form of http: // host/webappprefix/urltest2/anything. XML file (that is, deploydemo/WEB-INF/web. XML.
4. Disable the activator servlet.
There are two main ways to disable this default URL:
L re-map/servlet/mode in each web application.
L disable the global activator servlet.
4.1 re-map/servlet/URL Mode
In a specific web application, it is very easy to process URLs starting with http: // host/webappprefix/servlet. All you need to do is create an error message Servlet and use the URL-pattern element discussed in the previous section to redirect all matching requests to the servlet. As long as you simply use:
XML Code
<URL-pattern>/servlet/* </url-pattern>
4.2 global inactivate: Tomcat
The method used to disable the default URL in Tomcat 4 is different from that used in Tomcat 3. The following two methods are described:
1. Disable the activator: Tomcat 4
Tomcat 4 closes the activator servlet in the same way as before, that is, it closes the servlet using the URL-mapping element in Web. xml. The difference is that Tomcat uses a server-specific global web in install_dir/CONF. XML file, which is previously used to store standard web in the WEB-INF directory of each web application. XML file.
Therefore, to disable the activator servlet in Tomcat 4, simply comment out the/servlet/* URL ing item in install_dir/CONF/Web. XML, as shown below:
XML Code
<Servlet-mapping>
<Servlet-Name> invoker </servlet-Name>
<URL-pattern>/servlet/* </url-pattern>
</Servlet-mapping>
2. inactivate: tomcat3
In Apache Tomcat version 3, The invokerinterceptor item is listed in install_dir/CONF/server. XML to globally disable the default servlet URL. For example, the following section prohibits the use of a part of the server. xml file of the default servlet URL.
XML Code
<! --
<Requsetinterceptor classname = "org. Apache. tomcat. Request. invokerinterceptor" DEBUG = "0" prefix = "/servlet/"/>
-->
5. initialize and pre-load Servlet and JSP pages
The following describes how to control the starting behaviors of Servlet and JSP pages. In particular, it explains how to assign initialization parameters and how to change the time when the server loads Servlet and JSP pages during its lifecycle.
5.1 assign servlet initialization parameters.
Use the init-Param element to provide initialization parameters to servlet. The init-Param element has sub-elements of param-name And param-value. For example, in the following example, if initservlet is accessed using its Registration Name (inittest), it will be able to call getservletconfig () from its method (). getinitparameter ("param1") to get "value 1", call getservletconfig (). getinitparameter ("param2") gets "2 ".
XML Code
<Servlet>
<Servlet-Name> inittest </servlet-Name>
<Servlet-class> moreservlets. initservlet </servlet-class>
<Init-param>
<Param-Name> param1 </param-Name>
<Param-value> value1 </param-value>
</Init-param>
<Init-param>
<Param-Name> param2 </param-Name>
<Param-value> 2 </param-value>
</Init-param>
</Servlet>
6. Declare a filter
Servlet Version 2.3 introduces the concept of filters. Although all servers that support servlet API 2.3 Support filters, to use filter-related elements, you must use the DTD of Version 2.3 in Web. xml.
Filters can intercept and modify requests that enter a servlet or JSP page or send requests from a servlet or JSP page. Before executing a servlet or JSP page, you must execute the dofilter method of the first related filter. When the filter calls dofilter for its filterchain object, it executes the next filter in the chain. If no other filter exists, the servlet or JSP page is executed. Filters have full access to the servletrequest object. Therefore, they can view the client name and find the cookie. To access the servlet or JSP page output, the filter can wrap the response object in a stand-in object, for example, accumulating the output to a buffer. After calling the dofilter method of the filterchain object, the filter can check the buffer. If necessary, modify the method and then transmit it to the client.
Once a filter is created. in XML, use the filter element, filter-Name (any name), file-class (fully qualified class name), and (optional) Init-Params sub-element to declare it. Note that the elements are stored on the web. the order of the Web-app elements in XML is not arbitrary; the Order required by the server (but not required) is allowed, and some servers actually do the same. Note that all filter elements must appear before any filter-mapping element, and the filter-mapping element must appear before all servlet or servlet-mapping elements.
For example, given the reportfilter class, you can make the following filter declaration in Web. xml. It associates the name reporter with the actual class reportfilter (located in the moreservlets package.
XML Code
<Filter>
<Filter-Name> reporter </filter-Name>
<Filter-class> moresevlets. reportfilter </filter-class>
</Filter>
Once a filter is named, you can use the filter-mapping element to associate it with one or more servlet or JSP pages. There are two options for this job.
First, you can use the filter-Name and servlet-name sub-elements to match this filter with a specific servlet name (this servlet name must be later in the same web. use the servlet element declaration in the XML file) for association. For example, the following program snippet indicates that the system runs a filter named reporter as long as a custom URL is used to access the servlet or JSP page named someservletname.
XML Code
<Filter-mapping>
<Filter-Name> reporter </filter-Name>
<Servlet-Name> someservletname </servlet-Name>
</Filter-mapping>
Second, you can use the filter-Name and URL-pattern sub-elements to associate the filter with a set of servlet, JSP page, or static content. For example, the program fragment of the photo surface indicates that the system runs a filter named reporter as long as it accesses any URL in the Web application.
XML Code
<Filter-mapping>
<Filter-Name> reporter </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>
7. Specify the welcome page
What happens if a user provides a URL containing a directory name but not a file name like http: // host/webappprefix/directoryname? Can the user get a directory table? An error? Or standard file content? If the content of the standard file is index.html#index.jsp?default.html=default.htm or something else?
The welcome-file-list element and its auxiliary welcome-file element solve this fuzzy problem. . If neither of them is found, the result depends on the server used (such as a directory list ).
XML Code
<Welcome-file-List>
<Welcome-File> index. jsp </welcome-File>
<Welcome-File> index.html </welcome-File>
</Welcome-file-List>
8. Page for error handling
Now I know that you will never make mistakes when developing Servlet and JSP pages, and all your pages are so clear that General programmers will not be confused by them. However, people always make mistakes. Users may provide unspecified parameters, use incorrect URLs or cannot provide required form field values. In addition, other developers may be less careful. They should have some tools to overcome their own shortcomings.
The error-page element is used to overcome these problems. It has two possible child elements: Error-code and exception-type. The first child element, error-code, indicates the URL used when the given HTTP Error code appears. The second child element excpetion-type indicates the URL used when a given Java exception occurs but is not captured. Both error-code and exception-type use the location element to indicate the corresponding URL. This URL must start. The page at the location indicated by location can access error information by looking for two special attributes of the httpservletrequest object. These two attributes are javax. servlet. error. status_code and javax. servlet. error. message.
You can recall that it is important to declare the child elements of web-app in the correct order in Web. xml. Remember that the error-page appears near the end of the web. xml file, after servlet, servlet-name, and welcome-file-list.
8.1 error-code element
To better understand the value of the error-code element, consider the reflection of most sites if the file name is incorrectly entered. In this case, a 404 error message is displayed, indicating that the file cannot be found, but no more useful information is provided. On the other hand, you can try to output an unknown file name at http://www.microsoft.com/?http://www.ibm.com/ or especially at the http://www.bea.com. This generates useful messages, which provide selectable locations for searching pages of interest. Providing such useful error pages is very valuable for Web applications. In fact, the RM-error-page sub-element ). The HTML form provided by form-login-page must have a j_security_check action attribute, a text field named j_username, and a password field named j_password.
For example, listing 5-19 instructs the server to use form-based verification. A page named login. jsp in the top-level directory of the Web application collects user names and passwords, and failed logins are reported by pages named login-error.jsp in the same directory.
Program listing 5-19 web. XML (excerpt from login-config)
XML Code
<? XML version = "1.0" encoding = "ISO-8859-1"?>
<! 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>
<! --... -->
<Security-constraint>... </security-constraint>
<Login-config>
<Auth-method> form </auth-method>
<Form-login-config>
<Form-login-page>/login. jsp </form-login-page>
<Form-error-page>/login-error.jsp </form-error-page>
</Form-login-config>
</Login-config>
<! --... -->
</Web-app>
9.2 restrict access to web resources
You can now specify the authentication method used by the server. "Amazing," you said, "unless I can specify a URL to receive protection, it will be of little use. "That's right. It is the purpose of the security-constriaint element to identify these URLs and indicate what protection they should obtain. This element should appear in the web. xml before the login-config. It contains possible sub-elements: Web-resource-collection, Auth-constraint, user-data-constraint, and display-name. The following sections describe them.
L web-resource-collection
This element determines the resources to be protected. All security-constraint elements must contain at least one web-resource-collection item. This element is composed of a Web-resource-name element that gives an arbitrary identifier name, a URL-pattern element that determines the URL to be protected, and an HTTP command that indicates the applicable protection (get, post, etc, the HTTP-method element is composed of an optional description element that provides information. For example, the following web-resource-collection item (in the security-constratint element) indicates that all documents in the proprietary directory of the Web application should be protected.
XML Code
<Security-constraint>
<Web-resource-coolection>
<Web-resource-Name> proprietary </Web-resource-Name>
<URL-pattern>/propritary/* </url-pattern>
</Web-resource-coolection>
9.3 assign a role name
So far, the discussions have concentrated on the security issues fully handled by containers (servers. However, Servlet and JSP pages can also handle their own security issues.
For example, the container may allow the user to access an additional page that is closely followed by the supervisor from the bigwig or bigcheese role, but only allow the bigwig user to modify the parameters of this page. A common method to achieve more detailed control is to call the isuserinrole method of httpservletrequset and modify the access accordingly.
The Servlet's security-role-ref sub-element provides an alias for the security role name that appears in the server's dedicated password file. For example, if you have compiled a servlet that calls request. isuserinrole ("boss"), but later the servlet was used in a server where its password file calls the role manager instead of the boss. The following program section enables the servlet to use either of the two names.
XML Code
<Servlet>
<! --... -->
<Security-role-ref>
<Role-Name> boss </role-Name> <! -- New alias -->
<Role-link> Manager </role-link> <! -- Real name -->
</Security-role-ref>
</Servlet>
10 Control Session Timeout
If a session is not accessed for a certain period of time, the server can discard it to save memory. You can use the setmaxinactiveinterval method of httpsession to directly set the timeout value of individual session objects. If this method is not used, the default timeout value is determined by the specific server. However, the session-config and session-Timeout elements can be used to provide a clear timeout value for all servers. The unit of timeout value is minute. Therefore, the default session timeout value is set to three hours (180 minutes) in the following example ).
XML Code
<Session-config>
<Session-Time Out> 180 </session-Timeout>
</Session-config>
11 docization of Web Applications
More and more development environments begin to provide direct support for servlet and JSP. Examples include Borland JBuilder Enterprise Edition, Macromedia ultradev, Allaire JRun Studio (which was acquired by Macromedia at the time of writing this article) and IBM sans Aage for Java.
A large number of web. XML elements are not only designed for servers, but also for visual development environments. They include icon, display-name, and discription.
You can recall that it is important to declare web-app sub-elements in proper order in Web. xml. However, remember that the icon, display-name, and description are the first three valid elements in the Web-app element of Web. xml.
L icon
The icon element indicates that the GUI tool can represent one or two image files of a Web application. You can use the small-Icon element to specify a 16x16 GIF or JPEG image, and use the large-Icon element to specify a 32x32 image. The following is an example:
XML Code
<Icon>
<Small-Icon>/images/small-book.gif </small-Icon>
<Large-Icon>/images/tome.jpg </large-Icon>
</Icon>
L display-name
The display-name element provides a GUI tool that may be used to mark a name of the Web application. The following is an example.
<Display-Name> Rare Books </display-Name>
L description
The description element provides explanatory text as follows:
XML Code
<Description>
This web application represents the store developed for rare-books.com, an online bookstore specializing in rare and limited-edition books.
</Description>
12. Associated files and MIME types
Generally, servers have a method that allows web site administrators to associate file extensions with media. For example, an image/jpeg mime type is automatically assigned to a file named mom.jpg. However, if your web application has several unusual files, you want to ensure that they are allocated to some MIME type when sent to the client. Mime-mapping elements (with extension and mime-type subelements) provide this guarantee. For example, the following code instructs the server to allocate the MIME type of application/X-FUBAR to all files ending with. Foo.
XML Code
<Mime-mapping>
<Extension> Foo </extension>
<Mime-type> application/X-FUBAR </mime-type>
</Mime-mapping>
13PositioningTLD
The JSP taglib element has a necessary URI attribute, which gives the location of a TLD (TAG library descriptor) file relative to the Web application root. The actual name of the TLD file may change when a new tag library version is released, but we want to avoid changing all existing JSP pages. In addition, you may want to use a short URI that keeps the taglib element concise. This is where the taglib element of the deployment descriptor file comes in handy. Taglib contains two sub-elements: taglib-Uri and taglib-location. The taglib-Uri element should match the URI attribute used for the JSP taglib element. The taglib-location element shows the actual location of the TLD file. For example, if you put the file chart-tags-1.3beta.tld in webapp/WEB-INF/TLDs. Now, assume that web. xml contains the following content in the Web-app element.
XML Code
<Taglib>
<Taglib-Uri>/charts. TLD </taglib-Uri>
<Taglib-location>/WEB-INF/TLDs/chart-tags-1.3beta.tld </taglib-location>
</Taglib>
14 specified application event listener
The Application Event listener is a notification class when the servlet environment or session object is created or modified. These are new content in servlet Specification Version 2.3. Here we only briefly describe the usage of Web. xml used to register a listener to a web application.
Registering a listener involves placing a listener element in the Web-app element of Web. xml. In the listener element, the listener-class Element lists the complete qualified class names of the listener, as shown below:
XML Code
<Listener>
<Listener-class> package. listenerclass </listener-class>
</Listener>