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?
Welcome
-The file-list element and its auxiliary welcome-file element solve this fuzzy problem. For example, the following web. xml item indicates that if a URL provides a directory
If the file name is not provided, the server should first upload index.jsp, and then upload index.html. If neither of them is found, the result depends on the server used (such as a directory)
List ).
<Welcome-file-List>
<Welcome-File> index. jsp </welcome-File>
<Welcome-File> index.html </welcome-File>
</Welcome-file-List>
Although many servers follow this behavior by default, this is not necessarily the case. Therefore, it is a good habit to explicitly use Welcom-file-list to ensure portability.
8. Page for error handling
Now I understand that you are developing Servlet and
JSP pages never make mistakes, and all your pages are so clear that common programmers will not be confused by them. However, people always make mistakes, and users may provide unspecified parameters,
Use an incorrect URL or provide a required form field value. In addition, other developers may be less careful. They should have some tools to overcome their own shortcomings.
Error-page
Elements are used to overcome these problems. It has two possible child elements: Error-code and exception-type. The first sub-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. Location
On the page, you can find two special attributes of the httpservletrequest object to access error information. 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 www.microsoft.com or www.ibm.com, or especially at 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 http://www.plinko.net/404/ is dedicated to the site for the 404 error page content. This site contains the best, worst, and most funny 404 pages from around the world.
The JSP page is provided in step 5-13 of the program list, which can be returned to the client that provides the location program name. In program list 5-14, the specified program list 5-13 is used as the Web. xml of the page displayed when Error Code 404 is returned. Note that the URL displayed in the browser is still provided by the client. The error page is a background implementation technology.
Most
Later, remember that the default configuration of ie5 obviously does not comply with HTTP specifications. It ignores the error message generated by the server, but displays its own standard error information. Go to the Tools menu and select
Internet Options, click Advanced and cancel show friendly HTTP Error message to solve this problem.
Procedure 5-13 notfound. jsp
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head> <title> 404: Not found </title> <Body bgcolor = "# fdf5e6">
<H2> error! </H2>
I'm sorry, but I cannot find a page that matches
<% = Request. getrequesturi () %> On the system. Maybe you shoshould
Try one of the following:
<Ul>
<Li> go to the server's <a href = "/"> Home page </a>.
<Li> search for relevant pages. <br>
<Form action = "http://www.google.com/search">
<Center>
Keywords: <input type = "text" name = "Q"> <br>
<Input type = "Submit" value = "Search">
</Center>
</Form>
<Li> admire a random multiple of 404:
<% = 404 * (INT) (1000 * Math. Random () %>.
<Li> try a <a href = "http://www.plinko.net/404/rndindex.asp"
Target = "_ blank">
Random 404 error message </a>. From the amazing and
Amusing plinko.net <a href = "http://www.plinko.net/404/">
404 archive </a>.
</Ul>
</Body>
Program list 5-14 web. XML (excerpt from the error page indicating the HTTP Error 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>
<Error-page>
<Error-code> 404 </error-code>
<Location>/notfound. jsp </location>
</Error-page>
<! --... -->
</Web-app>
8.2 exception-type element
Error
-When the code element processes a request and generates a specific HTTP status code. However, it is also common to return 200 for servlet or JSP pages but generate runtime exceptions.
What should we do? This is exactly where the exception-type element is to be processed. You only need to provide the following two things: a fully qualified exception class and a location:
<Error-page>
<Exception-type> packagename. classname </exception-type>
<Location>/someurl </location>
</Error-page>
This
Sample: if any servlet or JSP page in the Web application generates a specific type of uncaught exception, the specified URL is used. This exception type can be a standard type, such
Javax. servletexception, java. Lang. outofmemoryerror, or an exception specific to your application.
Example
For example, in the program listing 5-15, an exception class named dumb1_exception is provided, which can be used to specifically mark programmers with less experience (not to say that your development team must
Such a person. This class also contains a static method named dangerouscomputation, which generates exceptions of this type from time to time. Program list 5-16
Call a JSP page of dangerouscompution for a random integer. When this exception is thrown, such as
Exception-type indicates that DDE. jsp (program list 5-17) is displayed on the client ). Figure 5-16 and figure 5-17 show the lucky and unfortunate results respectively.
Program listing 5-15 dumb1_exception. Java
Package moreservlets;
/** Exception used to flag participant ularly onerous
Programmer blunders. Used to restrict strate
Exception-type web. XML element.
* <P>
* Taken from more servlets and assumerver pages
* From Prentice Hall and Sun Microsystems press,
* Http://www.moreservlets.com /.
* & Copy; 2002 Marty Hall; may be freely used or adapted.
*/
Public class dumb1_exception extends exception {
Public dumb1_exception (){
Super ("duh. What was I * thinking *? ");
}
Public static int dangerouscomputation (int n)
Throws dumbdeveloperexception {
If (n <5 ){
Return (n + 10 );
} Else {
Throw (New dumb1_exception ());
}
}
}
Program list 5-16 riskypage. jsp
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head> <title> risky JSP page </title> <Body bgcolor = "# fdf5e6">
<H2> risky calculations </H2>
<% @ Page import = "moreservlets. *" %>
<% Int n = (INT) (10 * Math. Random (); %>
<Ul>
<Li> N: <% = n %>
<Li> dangerouscomputation (n ):
<% = Dumb1_exception. dangerouscomputation (n) %>
</Ul>
</Body>
Procedure 5-17 DDE. jsp
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head> <title> dumb </title> <Body bgcolor = "# fdf5e6">
<H2> dumb developer </H2>
We're re brain dead. Consider using our competitors.
</Body>
Program list 5-18 web. XML (excerpt from the error page specified for the exception)
<? 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>
<! --... -->
<Servlet>... </Servlet>
<! --... -->
<Error-page>
<Exception-type>
Moreservlets. dumb1_exception
</Exception-type>
<Location>/DDE. jsp </location>
</Error-page>
<! --... -->
</Web-app>
9 provide security
The related elements in Web. XML are used to provide security for the built-in functions of the server.
9.1 specify the Verification Method
Enable
Use the login-confgi element to specify how the server verifies the user attempting to access the protected page. It contains three possible child elements: Auth-method and realm.
-Name and form-login-config. The login-config element should appear near the end of the web. xml deployment descriptor file, followed
After the security-constraint element.
L auth-Method
This sub-element of login-config lists the specific authentication mechanisms that the server will use. Valid values: basic, digest, form, and client-cert. The server only needs to support basic and form.
Basic
Indicates that standard HTTP authentication should be used. In this authentication, the server checks the Authorization header. If this header is missing, a 401 status code and a WWW-
Authenticate header. This causes the client to pop up a dialog box for entering the Authorization header. This mechanism rarely or does not provide protection against attackers.
Internet connections (for example, by executing an information package detection device on the client's subnet), because the user name and password are sent in simple reversible base64 encoding, they are easy
Good. All compatible servers must support basic verification.
Digest indicates that the client should use encrypted Digest
The user name and password are transmitted in authentication form. This provides higher security against network intercept than basic verification, but this encryption is more secure than that used by SSL (https ).
Method is easier to crack. However, this conclusion is sometimes meaningless because few browsers currently support digest authentication, so servlet containers do not need to support it.
Form
It indicates that the server should check the reserved session cookie and redirect users who do not have it to a specified Login page. This login page should contain a regular HTML form that collects user names and passwords. In
After login, the user is tracked using session-level cookies. Although complex, form verification is not more secure than basic verification to prevent network snoop. If necessary, you can arrange
Additional protection such as SSL or network layer security (such as IPSEC or VPN. All compatible servers must support form verification.
Client-Cert requires that the server must use HTTPS (HTTP over SSL) and use the user's public key certificate (pulic key Certificat) to verify the user. This provides strong security protection against network interception, but only J2EE-compatible servers need to support it.
L realm-name
This element is used only when auth-method is basic. It indicates the name of the security domain used by the browser in the title of the corresponding dialog box and as part of the Authorization header.
L form-login-config
This
The element is applicable only when auth-method is form. It specifies two pages that contain HTML forms that collect user names and passwords (using form-login-
Page sub-element), used to indicate the page that fails verification (using the form-error-page sub-element ). The HTML form given 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 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
Now
In, you can 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. Specify these URLs and describe them
Which protection should be obtained is exactly the purpose of the security-constriaint element. This element should appear in the web. xml before the login-config. It
Contains possible sub-elements: Web-resource-collection, Auth-constraint, and user-data-
Constraint and display-name. The following sections describe them.
L web-resource-collection
This yuan
Determine the resources to be protected. All security-constraint elements must contain at least one web-resource-collection item. This element is composed
A Web-resource-name element that identifies any name, a URL-pattern element that identifies the URL to be protected, and
The HTTP-method element of an HTTP command (such as get and post, which defaults to all methods) and an optional description element that provides information. For example
The web-resource-collection item (in the security-constratint element) indicates that the Web application's proprietary directory
All documents should be protected.
<Security-constraint>
<Web-resource-coolection>
<Web-resource-Name> proprietary </Web-resource-Name>
<URL-pattern>/propritary/* </url-pattern>
</Web-resource-coolection>
<! --... -->
</Security-constraint>
Heavy
Note that URL-pattern is only applicable to clients that directly access these resources. In particular, it is not suitable for exploitation through the MVC Architecture
The page accessed by requestdispatcher, or is not suitable for pages accessed by means similar to JSP: forward. This kind of imbalance is good if it is used properly.
. For example, servlet can use the MVC Architecture to search for data, put it into the bean, send a request to the JSP page that extracts data from the bean, and display it. We want to ensure that we will never go straight.
Access the protected JSP page, but access it by creating the bean servlet that the page will use. URL-pattern and Auth-contraint Elements
This guarantee can be provided by declaring that no user is allowed to directly access the JSP page. However, such uneven behaviors may cause developers to relax their vigilance, so that they occasionally provide unrestricted access to protected resources.
Access.
L Auth-Constraint
Although the web-resource-collention element quality indicates which URLs should be protected,
However, the auth-constraint element indicates which users should have access to protected resources. This element should contain one or more user categories that identify users with access permissions role-
The name element and the description element that contains (optional) a role description. For example, the security-constraint element in the following web. xml file
Only the user specified as administrator or big kahuna (or both) has access to the specified resource.
<Security-constraint>
<Web-resource-coolection>... </Web-resource-coolection>
<Auth-constraint>
<Role-Name> administrator </role-Name>
<Role-Name> Kahuna </role-Name>
</Auth-constraint>
</Security-constraint>
It is important to realize that the portable part of this process has ended. How the server determines which users are in any role and how it stores the user's password depends on the specific system.
For example, Tomcat uses install_dir/CONF/tomcat-users.xml to associate the user name with the role name and password, as shown in the following example, it points out that the user Joe (password bigshot) and Jane (password enaj) belongs to the Administrator and Kahuna roles.
<Tomcat-users>
<User name = "Joe" Password = "bigshot" roles = "Administrator, Kahuna"/>
<User name = "Jane" Password = "enaj" roles = "Kahuna"/>
</Tomcat-users>
L user-data-Constraint
This
Optional elements indicate that any transport layer protection is used when accessing related resources. It must contain a transport-guarantee sub-element (valid value: none,
Integral or confidential), and optional include a description element. If transport-guarantee is set to none
The communication protocols used are not restricted. The integral value indicates that the data must be transmitted in a way that prevents the person who intercepts it from reading it. In principle (and in future HTTP versions ),
There may be differences between integral and confidential, but in the current practice, they simply require SSL. For example, the following command indicates that the server only allows
HTTPS connection:
<Security-constraint>
<! --... -->
<User-data-constraint>
<Transport-guarantee> confidential </transport-guarantee>
</User-data-constraint>
</Security-constraint>
L display-name
This rarely used sub-element of security-constraint gives a name for security constraints that may be used by GUI tools.
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.
Example
For example, the container may allow the user to access an additional page from the bigwig or bigcheese role, but only allow the bigwig user to modify the parameters of this page. Complete this
A common method for more detailed control is to call the isuserinrole method of httpservletrequset and modify the access accordingly.
Servlet
The security-role-ref sub-element provides an alias for the security role name that appears in the server-specific password file. For example, if you write a call
Request. isuserinrole ("boss") servlet, but later this servlet was used in a password file to call the role manager instead
Is In The Boss server. The following program section enables the servlet to use either of the two names.
<Servlet>
<! --... -->
<Security-role-ref>
<Role-Name> boss </role-Name> <! -- New alias -->
<Role-link> Manager </role-link> <! -- Real name -->
</Security-role-ref>
</Servlet>
You can also use the security-role element in the Web-app to provide a global list of all security roles that appear in the role-name element. Separate life roles make advanced ide easy to process security information.
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 you do not use
In this way, the default timeout value is determined by the specific server. However, the session-config and session-Timeout elements can be used to provide
A specific timeout value. The unit of timeout value is minute. Therefore, the default session timeout value is set to three hours (180 minutes) in the following example ).
<Session-config>
<Session-Time Out> 180 </session-Timeout>
</Session-config>
11 docization of Web Applications
More and more development environments begin to provide
Servlet and JSP support. Examples include Borland JBuilder Enterprise Edition and Macromedia.
Ultradev, Allaire JRun Studio (acquired by Macromedia when writing this article ),
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:
<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:
<Description>
This web application represents the store developed
Rare-books.com, an online bookstore specializing in rare
And limited-edition books.
</Description>
12. Associated files and MIME types
Generally, a server has a Web site administrator
Method for associating a file extension with a media file. 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 element (with extension and mime-type child
Elements. For example, the following code instructs the server to allocate the MIME type of application/X-FUBAR to all files ending with. Foo.
<Mime-mapping>
<Extension> Foo </extension>
<Mime-type> application/X-FUBAR </mime-type>
</Mime-mapping>
Maybe your web application wants to reload the standard ing. For example, the following code tells the server to specify the. PS file as plain text (text/plain) instead of PostScript (Application/postscript) when sending it to the client ).
<Mime-mapping>
<Extension> ps </extension>
<Mime-type> application/postscript </mime-type>
</Mime-mapping>
13 positioning TLD
JSP
The taglib element has a required URI attribute, which provides a TLD (TAG Library
The location of the file relative to the root of the Web application. 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
Child elements: taglib-Uri and taglib-location. The taglib-Uri element and
The URI attributes of the taglib element are matched. The taglib-location element shows the actual location of the TLD file. For example, if you set the file chart-tags-
1.3beta.tld is placed in webapp/WEB-INF/TLDs. Now, assume that web. xml contains the following content in the Web-app element.
<Taglib>
<Taglib-Uri>/charts. TLD </taglib-Uri>
<Taglib-location>
/WEB-INF/TLDs/chart-tags-1.3beta.tld
</Taglib-location>
</Taglib>
After providing this description, the JSP page can use the tag library in the simplified form below.
<% @ Taglib uri = "/charts. TLD" prefix = "someprefix" %>
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:
<Listener>
<Listener-class> package. listenerclass </listener-class>
</Listener>
Although
However, the structure of the listener element is very simple, but do not forget that the sequence of child elements in the Web-app element must be correctly given. The listener element is located in all servlets.
Before and after all filter-mapping elements. In addition, because the application lifetime listener is new in Serlvet Specification Version 2.3, you must use
Version 2.3 of the web. xml dtd, instead of Version 2.2.
For example, a simple listener named contextreporter is provided in the program list 5-20,
When the servlet-context of the Web application is established (such as loading the web application) or eliminated (such as the server is disabled), a message is displayed on the standard output. Program list 5-21
Part of the web. xml file required for the listener registration.
Program list 5-20 contextreporterjava
Package moreservlets;
Import javax. servlet .*;
Import java. util .*;
/** Simple listener that prints a Report on the standard output
* When the servletcontext is created or destroyed.
* <P>
* Taken from more servlets and assumerver pages
* From Prentice Hall and Sun Microsystems press,
* Http://www.moreservlets.com /.
* & Copy; 2002 Marty Hall; may be freely used or adapted.
*/
Public class contextreporter implements servletcontextlistener {
Public void contextinitialized (servletcontextevent event ){
System. Out. println ("context created on" +
New Date () + ".");
}
Public void contextdestroyed (servletcontextevent event ){
System. Out. println ("context destroyed on" +
New Date () + ".");
}
}
Program list 5-21 web. XML (declare an excerpt from a listener)
<? 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>
<! --... -->
<Filter-mapping>... </Filter-mapping>
<Listener>
<Listener-class> package. listenerclass </listener-class>
</Listener>
<Servlet>... </servlet>
<! --... -->
</Web-app>
15 J2EE Elements
This section describes the Web. XML elements used as part of the J2EE environment. For more information, see Chapter 1.3 of Java 2 plantform Enterprise Edition version 5th in http://java.sun.com/j2ee/j2ee-4873-fr-spec..pdf.
L distributable
Distributable
It is pointed out that web applications are programmed in this way: servers supporting clusters can securely distribute web applications on multiple servers. For example, a distributed application must only use
The serializable object is the attribute of its httpsession object, and you must avoid using instance variables (fields) for continuity. Distributable element straight
After the discription element is connected and does not contain child elements or data, it is just a flag as follows.
<Distributable/>
L Resource-env-ref
Resource
-The env-ref element declares a management object related to a resource. This element is composed of an optional description element and a resource-env-ref-
Name element (a JNDI name relative to the Java: COMP/ENV Environment) and a resource-env-type element (specifying the fully qualified resource type)
Class), as follows:
<Resource-env-ref>
<Resource-env-ref-Name>
JMS/stockqueue
</Resource-env-ref-Name>
<Resource-env-ref-type>
Javax. JMS. Queue
</Resource-env-ref-type>
</Resource-env-ref>
L env-entry
Env
-The entry element declares the environment items of the Web application. It consists of an optional description element and an env-entry-name element (:
COMP/ENV Environment JNDI name), an env-entry-value element (item value), and an env-entry-type element (Java. Lang Program
The fully qualified class name of a type in the package, including Java. Lang. boolean and Java. Lang. String. The following is an example:
<Env-entry>
<Env-entry-Name> minamout </env-entry-Name>
<Env-entry-value> 100.00 </env-entry-value>
<Env-entry-type> minamout </env-entry-type>
</Env-entry>
L EJB-ref
EJB
-The ref element declares the application to the main directory of an EJB. It consists of an optional description element and an EJB-ref-name element (relative to Java:
EJB application of COMP/ENV), an EJB-ref-type element (bean type, entity or session), and a home element (bean master
Full-qualified Directory Interface Name), a remote element (full-qualified bean remote interface name), and an optional EJB-link element (another of the current bean link)
Bean name.
L EJB-local-ref
The EJB-local-ref element declares a reference to the local directory of an EJB. In addition to replacing home with local-home, this element has the same attributes as the EJB-ref element and is used in the same way.