Configuration of Web. XML in Servlet (i)

Source: Internet
Author: User
Tags event listener apache tomcat

1 defining headers and root elements

The deployment descriptor file, like all XML files, must start with an XML header. This header declares the XML version that can be used and gives the character encoding of the file.
The DOCYTPE declaration must immediately appear after this header. This statement tells the server which version of the servlet specification is applicable (for example, 2.2 or 2.3) and specifies a DTD (document type definition, doc-types definitions) that manages the syntax for the remainder of this file.
The top-level (root) element of all deployment descriptor files is Web-app. Note that XML elements are not like HTML, and they are case-sensitive. Therefore, Web-app and Web-app are not legal, web-app must be lowercase.

2 element order within the deployment descriptor file

XML elements are not only case-sensitive, but they are also sensitive to the order in which they appear in other elements. For example, the XML header must be the first item in the file, the DOCTYPE declaration must be the second item, and the Web-app element must be the third item. Within the Web-app element, the order of the elements is also important. Servers do not necessarily enforce this order, but they allow (in fact some servers do) a complete denial of the execution of Web applications that contain elements that are not in the correct order. This means that the Web. xml file using the non-standard element order is not portable.
The following list gives all the necessary order for the legitimate elements to appear directly within the Web-app element. For example, this list describes servletThe element must appear before all servlet-mapping elements. Please note that all of these elements are optional. Therefore, you can omit an element, but you cannot put it in an incorrect position.
l iconThe icon element indicates the location of the IDE and GUI tools used to represent one and two image files of the Web App.
L Display-nameThe Display-name element provides a name that GUI tools may use to mark this particular Web app.
L DescriptionThe description element gives explanatory text related to this.
L Context-paramThe Context-param element declares an application-scoped initialization parameter.
L FilterThe filter element associates a name with a class that implements the Javax.servlet.Filter interface.
L filter-mappingOnce a filter is named, it should be associated with one or more servlet or JSP pages using the filter-mapping element.
LlistenerVersion 2.3 of the Servlet API adds support for event listeners, which are notified when a session or servlet environment is established, modified, and deleted. The listener element indicates the event listener class.
LservletWhen you set initialization parameters or custom URLs to a servlet or JSP page, you must first name the servlet or JSP page. The servlet element is used to accomplish this task.
lservlet-mappingThe server typically provides a default url:http://host/webappprefix/servlet/servletname for the servlet. However, this URL is often changed so that the servlet can access the initialization parameters or make it easier to handle relative URLs. Use the servlet-mapping element when changing the default URL.
Lsession-configIf a session is not accessed for a certain amount of time, the server can discard it to save memory. You can explicitly set a time-out value for a single Session object by using the Setmaxinactiveinterval method of HttpSession, or you can use the Session-config element to make a default timeout.
lmime-mappingThe mime-mapping element provides this assurance if the Web app has a particular file to think about and wants to ensure that they are assigned a specific MIME type.
lwelcom-file-listThe Welcome-file-list element indicates which file the server uses when it receives a URL that references a directory name instead of a file name.
L Error-pageThe Error-page element enables the page to be displayed when a specific HTTP status code is returned, or when a particular type of exception is thrown.
l taglibThe taglib element specifies an alias for the tag Library descriptor file (tag Libraryu descriptor files). This feature enables you to change the location of TLD files without editing the JSP pages that use those files.
L RESOURCE-ENV-REFThe Resource-env-ref element declares a management object that is associated with a resource.
L RESOURCE-REFThe Resource-ref element declares an external resource used by a resource factory.
L Security-constraintThe Security-constraint element formulates the URL that should be protected. It is used in conjunction with the Login-config element
L Login-configUse the Login-config element to specify how the server should authorize users attempting to access a protected page. It is used in conjunction with the Sercurity-constraint element.
L Security-roleThe Security-role element gives a list of security roles that will appear in the Role-name child elements of the security-role-ref element within the servlet element. Declaring roles separately makes it easier for advanced Ides to handle security information.
L Env-entryThe Env-entry element declares the environment item for the web App.
L EJB-REFThe Ejb-ref element declares a reference to the home directory of an EJB.
L EJB-LOCAL-REFThe Ejb-local-ref element declares the application of an EJB's local home directory.

3 assigning names and customizing the UL

One of the most common tasks done in Web. XML is to give a name and a custom URL to a servlet or JSP page. Assign a name with the servlet element and use the servlet-mapping element to associate the custom URL with the name you just assigned.
3.1 Assigning names
To provide initialization parameters, define a custom URL for a servlet or JSP page, or assign a security role, you must first give the servlet or JSP page a name. A name can be assigned through the servlet element. The most common formats include the servlet-name and Servlet-class child elements (within the Web-app element), as follows:
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>moreservlets. Testservlet</servlet-class>
</servlet>

This means that the servlet at Web-inf/classes/moreservlets/testservlet has been registered with the name test. Giving the servlet a name has two main meanings . First, the initialization parameters, the custom URL pattern, and other customizations refer to this servlet through this registration name instead of the class name. Second, you can use this name in a URL instead of a class name. Thus, using the definition just given, URL http://host/webAppPrefix/servlet/Test can be used for http://host/webAppPrefix/servlet/moreservlets.TestServlet sites.
Keep in mind that XML elements are not only case-sensitive, but also that the order in which they are defined is important. For example, all servlet elements within a WEB-APP element must precede all servlet-mapping elements (described in the next section), and also in sections 5.6 and 5.11, before the filter or document-related elements, if any. Similarly, the Servlet-name child elements of the servlet must also appear before Servlet-class. Section 5.2, "Order of elements in the deployment descriptor file" will detail this required order.
For example, the program listing 5-1 shows a simple servlet named Testservlet that resides in the Moreservlets package. Because this servlet is part of a WEB app rooted in a directory named Deploydemo, Testservlet.class is placed in Deploydemo/web-inf/classes/moreservlets. Listing 5-2 shows part of the Web. xml file that will be placed within the deploydemo/web-inf/. This web. xml file uses the Servlet-name and Servlet-class elements to associate the name test with Testservlet.class. Figure 5-1 and Figure 5-2 show the results when calling Testservlet with the default URL and the registration name, respectively.

Program Listing 5-1 Testservlet.java
Package moreservlets;

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;

/** simple servlets used to illustrate servlet naming
* and Custom URLs.
* <P>
* Taken from more servlets and JavaServer Pages
* FROM Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* &copy; 2002 Marty Hall; May is freely used or adapted.
*/

public class Testservlet extends HttpServlet {
public void doget (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
String uri = Request.getrequesturi ();
Out.println (Servletutilities.headwithtitle ("Test Servlet") +
"<body bgcolor=/" #FDF5E6/">/n" +
""</BODY></HTML>");
}
}


Program Manifest 5-2 Web. XML (Description of an excerpt from the servlet name)
<?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-name>Test</servlet-name>
<servlet-class>moreservlets. Testservlet</servlet-class>
</servlet>
<!--...-->
</web-app>

3.2 Defining a custom URL
Most servers have a default Serlvet URL:
Http://host/webAppPrefix/servlet/packageName.ServletName. Although it is convenient to use this URL in development, we often expect another URL to be used for deployment. For example, you might need a URL that appears at the top of the Web app, such as Http://host/webAppPrefix/Anyname, and there are no servlet entries in this URL. The URL at the top level simplifies the use of relative URLs. Also, for many developers, the top-level URLs look shorter than the longer, more cumbersome default URLs.
In fact, it is sometimes necessary to use a custom URL. For example, you might want to turn off the default URL mapping to better enforce security restrictions or prevent users from accidentally accessing Servlets with no initialization parameters. If you disable the default URL, how do you access the servlet? Only custom URLs are used at this time.
To assign a custom URL, you can use the servlet-mapping element and its servlet-name and url-pattern child elements. The Servlet-name element provides an arbitrary name that can be used to refer to the corresponding Servlet;url-pattern that describes the URL relative to the Web app's root directory. The value of the Url-pattern element must start with a slash (/).
A simple excerpt of Web. XML is given below, 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 XML headers, DOCTYPE declarations, and Web-app enclosing elements are still required. Also, recall that the order in which the XML elements appear is not arbitrary. In particular, all servlet elements need to be placed before all servlet-mapping elements.
<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 pattern can also contain wildcard characters. For example, the following applet instructs the server to send all the URL prefixes starting with the Web app to: ASP ends the request to a servlet named Bashms.
<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 pages
Because JSP pages are converted to Sevlet, you naturally want to name the JSP page just like a named servlet. After all, JSP pages may benefit from initialization parameters, security settings, or custom URLs, just like normal serlvet. Although the background of the JSP page is actually a servlet, there is a critical suspicion that you do not know the actual class name of the JSP page (because the system chooses the name). Therefore, in order to name the JSP page, you can replace the jsp-file element with the SERVLET-CALSS element, as follows:
<servlet>
<servlet-name>Test</servlet-name>
<jsp-file>/TestPage.jsp</jsp-file>
</servlet>
The reason for naming a JSP page is exactly the same as for a named servlet: to provide a name to use with custom settings (such as initialization parameters and security settings), and to change the URL of the active JSP page (for example, so that multiple URLs can be processed by the same page, or remove the. jsp extension from the URL. However, when setting initialization parameters, it should be noted that the JSP page is using the Jspinit method instead of the Init method to read the initialization parameters.
For example, listing 5-3 shows a simple JSP page named Testpage.jsp, whose job is to print out the local part of the URL used to activate it. The testpage.jsp is placed at the top level of the Deploydemo application. Listing 5-4 shows the Web. xml file (that is, Deploydemo) that is used to assign a registered name pagename and then associate this registry name with a URL in the form of http://host/webAppPrefix/UrlTest2/anything. Part of the/web-inf/web.xml).

Program Listing 5-3 testpage.jsp
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE>
JSP Test Page
</TITLE>
</HEAD>
<body bgcolor= "#FDF5E6" >
</BODY>
</HTML>


Program listing 5-4 Web. XML (Description of the JSP page named excerpt)
<?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-name>PageName</servlet-name>
<jsp-file>/TestPage.jsp</jsp-file>
</servlet>
<!--...-->
<servlet-mapping>
<servlet-name> PageName </servlet-name>
<url-pattern>/UrlTest2/*</url-pattern>
</servlet-mapping>
<!--...-->
</web-app>


4 Disable Activator servlet

One reason to create a custom URL for a servlet or JSP page is to register the initialization parameters in the read from the init (servlet) or Jspinit (JSP page) method. However, initialization parameters can be used only when accessing a servlet or JSP page using a custom URL pattern or a registered name, which is not available when accessed with the default URL http://host/webAppPrefix/servlet/ServletName. Therefore, you might want to close the default URL so that no one will accidentally invoke the Init servlet. This process is sometimes referred to as banning the activator servlet, because most servers have a standard servlet registered with the default servlet URL and activate the actual servlet of the default URL app.
There are two main ways to disallow this default URL:
L REMAP the/servlet/mode in each Web App.
L global shutdown activator servlet.
It is important to note that while remapping the/servlet/pattern in each Web app is more than a complete ban on activating the servlet, remapping can be done in a completely portable way. Instead, the global disable Activator servlet is completely specific to the machine, and in fact some servers (such as servletexec) do not have such a choice. The following discussion discusses the policy of remapping/servlet/url mode for each web app. The details of the global disable Activator servlet in Tomcat are provided later in this section.
4.1 Remap/servlet/url mode
It is very easy to disallow the processing of URLs that start with http://host/webAppPrefix/servlet/in a particular Web application. All you need to do is create an error message servlet and use the Url-pattern element discussed in the previous section to turn all matching requests to that servlet. As long as it is simple to use:
<url-pattern>/servlet/*</url-pattern>
As a pattern in the servlet-mapping element.
For example, the program listing 5-5 shows part of the deployment descriptor file associated with the Sorryservlet servlet (program listing 5-6) and all URLs that begin with http://host/webAppPrefix/servlet/.

Program listing 5-5 Web. XML (Description of the JSP page named excerpt)
<?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-name>Sorry</servlet-name>
<servlet-class>moreservlets. Sorryservlet</servlet-class>
</servlet>
<!--...-->
<servlet-mapping>
<servlet-name> Sorry </servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
<!--...-->
</web-app>


Program Listing 5-6 Sorryservlet.java
Package moreservlets;

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;

/** simple servlets used to give error messages to
* Users who try to access default servlet URLs
* (i.e.,// Host/webappprefix/servlet/servletname)
* In the WEB applications that has disabled this
* behavior.
* <P>
* taken from + servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* HT tp://www.moreservlets.com/.
* &copy; 2002 Marty Hall; may be freely used or adapted.
*/

public class Sorryservlet extends HttpServlet {
public void doget (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
String title = "Invoker Servlet Disabled.";
Out.println (Servletutilities.headwithtitle (title) +
"<body bgcolor=/" #FDF5E6/">/n" +
"<H2>" + title + ""Sorry, access to Servlets by means of/n" +
"URLs that begin with/n" +
"http://host/webAppPrefix/servlet//n" +
"has been disabled./n" +
"</BODY></HTML>");
}

public void DoPost (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
Doget (request, response);
}
}

The


4.2 Global Disable Activator: Tomcat
The method used to close the default URL in Tomcat 4 is very different from that used in Tomcat 3. These two methods are described below:
1. Disable Activator: Tomcat 4
Tomcat 4 shuts down the activator servlet using the same method as before, which uses the url-mapping element in Web. XML to close. The difference is that Tomcat uses a global web. xml file that is dedicated to a server that is placed in install_dir/conf, with the standard Web. xml file stored in the Web-inf directory of each Web application.
Therefore, in order to turn off the activator servlet in Tomcat 4, simply annotate the/servlet/* URL mapping entry in Install_dir/conf/web.xml, as follows:
<!-- 
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/* </url-pattern>
</servlet-mapping>
-->
again, it should be noted that this item is located in the install_dir/ In the Conf tomcat-dedicated web. xml file, this file is not a standard web.
2. Disable activator: TOMCAT3
in Apache Tomcat version 3, through the install_dir/conf/ Server.xml the Invokerinterceptor item globally prohibits the default servlet URL from being commented out. For example, the following is part of the Server.xml file that prohibits using the default servlet URL.
<!-- 
<requsetinterceptor 
classname= "Org.apache.tomcat.request.InvokerInterceptor"
debug= "0" prefix= "/servlet/"/>
-->

5 initializing and pre-loading servlets and JSP pages

Here we discuss ways to control the startup behavior of Servlets and JSP pages. In particular, it explains how to allocate initialization parameters and how to change the time the server lifetime loads Servlets and JSP pages.
5.1 assigning servlet initialization parameters
The Init-param element is used to provide initialization parameters to the servlet, and the Init-param element has param-name and param-value child elements. For example, in the following example, if the Initservlet servlet is accessed using its registered name (Inittest), it will be able to invoke Getservletconfig () from its method. Getinitparameter ("param1") Get "Value 1" and call Getservletconfig (). Getinitparameter ("param2") for "2".
<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>
There are a few things to be aware of when initializing parameters are involved:
L return value。 The return value of Getinitparameter is always a string. Therefore, in the previous example, you can use Integer.parseint for param2 to obtain an int.
l initialization in JSP。 The JSP page uses jspinit instead of init. The JSP page also needs to use the Jsp-file element instead of the Servlet-class.
l default URL。 Initialization parameters are only available when accessing the servlet through their registered name or the custom URL pattern associated with their registered name. Therefore, in this example, the param1 and param2 initialization parameters will be available when the URL http://host/webAppPrefix/servlet/InitTest is used, but the URL is used http://host/ cannot be used when webappprefix/servlet/mypackage.initservlet.
For example, the program listing 5-7 shows a simple servlet named Initservlet that uses the Init method to set the FirstName and EmailAddress fields. Listing 5-8 shows the Web. xml file assigned the name Inittest to the servlet.
Program Listing 5-7 Initservlet.java
Package moreservlets;

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;

/** simple servlet used to illustrate servlet
* Initialization parameters.
* <P>
* Taken from more servlets and JavaServer Pages
* FROM Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* &copy; 2002 Marty Hall; May is freely used or adapted.
*/

public class Initservlet extends HttpServlet {
Private String firstName, EmailAddress;

public void init () {
ServletConfig config = getservletconfig ();
FirstName = Config.getinitparameter ("FirstName");
EmailAddress = Config.getinitparameter ("EmailAddress");
}

public void doget (HttpServletRequest request,
HttpServletResponse response)
throws Servletexception, IOException {
Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
String uri = Request.getrequesturi ();
Out.println (Servletutilities.headwithtitle ("Init Servlet") +
"<body bgcolor=/" #FDF5E6/">/n" +
" " <ul>/n "+
" <li>first name: "+ firstName +"/n "+
" < Li>email Address: "+ EmailAddress +"/n "+
" </ul>/n "+&NBSP;
" </BODY></HTML> ");
}
}


Program Manifest 5-8 Web. XML (Description of an excerpt of initialization parameters)
<?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-name>InitTest</servlet-name>
<servlet-class>moreservlets. Initservlet</servlet-class>
<init-param>
<param-name>firstName</param-name>
<param-value>Larry</param-value>
</init-param>
<init-param>
<param-name>emailAddress</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
<!--...-->
</web-app>

Configuration of Web. XML in Servlet (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.