[XML] Detailed description of Web.xml configuration

xiaoxiao2021-04-07  335

1 Defining the header and root element deployment descriptor files like all XML files must start with an XML header. This header declares can use the XML version and give the character encoding of the file. DOCYTPE declaration must immediately appear after this header. This declaration tells the server to which the version of the servlet specification (such as 2.2 or 2.3) is specified and specifying the DTD (Document Type Definition, document type definition) of the syntax of this file. The top (root) element of all deployment descriptor files is a web-app. Note that XML elements are unlike HTML, they are sensitive. Therefore, both web-app and web-app are illegal, and the web-app must be written. 2 Deployment Descriptor Document The XML element is not only sensitive, but also they are sensitive to the order in other elements. For example, the XML head must be the first item in the file, and the DOCTYPE declaration must be the second item, and the web-app element must be the third item. In the web-app element, the order of the elements is also important. The server is not necessarily forced to require this order, but they allow (actually some servers doing this) completely refuse to perform web applications that contain elements in order incorrect. This means that the Web.xml file used in the order of the non-standard element is unmistable. The following list gives all the order necessary for all legitimate elements that can appear in the web-app element. For example, this list Description servlet elements must appear before all servlet-mapping elements. Please note that all of these elements are optional. Therefore, a certain element can be omitted, but it cannot be placed in an incorrect position. l icon icon elements indicate that the IDE and GUI tools are used to represent one and two image files of the web application. l Display-name Display-Name element provides a GUI tool that may be used to mark a name for this particular web application. The L Description Description element gives an illustrative text associated with this. l Context-param context-param element declares initialization parameters within the application range. l Filter filter elements Associate a name with a class that implements the Javax.Servlet.Filter interface. l Filter-Mapping Once a filter is named, use the filter-mapping element to associate it with one or more servlets or JSP pages. l Listener Servlet API version 2.3 adds support for event listeners, and event listeners are notified when establishing, modifying, and deleting sessions or servlet environments. The Listener element indicates the event listener class. l Servlet When you set an initialization parameter or a custom URL to the servlet or JSP page, you must first name the servlet or JSP page. The servlet element is used to complete this task. l Servlet-Mapping Server typically provides a default URL for servlet:

http:// host / webappppprefix / servlet / servletname

. However, this URL is often changed so that servlets can access initialization parameters or more easily handle relative URLs. Using servlet-mapping elements when changing the default URL. l Session-config If a session is not accessed for a certain period of time, the server can discard it to save memory. The timeout value of a single session object can be explicitly set by using the HttpSession's setMaxinactiveInterVal method, or the default timeout value can be used to use the session-config element. l Mime-mapping If the web application has a special file, I hope to guarantee the assigned MIME type, then the mime-mapping element provides this guarantee. l Welcom-file-list welcome-file-list element indicates which file when receiving a directory name instead of a file name instead of a file name. l Error-Page Error-Page element allows the page that will be displayed when the particular type of abnormality is returned, or when the particular type of exception is thrown. l Taglib Taglib Elements Specify an alias for tag libraryu descriptor file. This feature allows you to change the location of the TLD file without editing the JSP page using these files. l Resource-Env-Ref Resource-Env-Ref element declares a management object related to the resource. l Resource-Ref Resource-Ref element declares an external resource used by a resource factory. l Security-constraint security-constraint Elements Develop the URL that should be protected. It combines L login-config elements to specify how to use the login-config element to specify how the server is authorized to access the protected page to try to access the protected page. It is used in combination with the Sercurity-Constraint element. l Security-role security-role elements give a list of secure roles that will appear in the Role-Name sub-elements of the security-role-ref elementality within the servlet element. Declaration of the role separately makes advanced IDE processing security information easier. l Env-entry env-entry elements declare the environment item of the web application. l EJB-REF EJB-REF Elements Declare a reference to the primary directory of an EJB. l Ejb-local-ref ejb-local-ref element declares an application of an EJB local host directory. 3 Assign Names and customized ULs One of the most common tasks completed in Web.xml is to give the servlet or JSP page to the name and custom URL. Use the servlet element to associate the custom URL with the just assigned name using the servlet-mapping element. 3.1 Assignment Name In order to provide initialization parameters, define a custom URL or assign a security role to the servlet or JSP page, you must first give the servlet or JSP page a name. A name can be assigned via the servlet element. The most common formats include servlet-name and servlet-class sub-elements (within a web-app element), as shown below: test moreservlets.testServlet This means that servlets in Web-INF / CLASSERVLET have been registered Test. It has two main meanings to servlet a name. First, initialize the parameters, custom URL mode, and other customizations this registration name rather than the class name references this servlet. Second, this name can be used in the URL instead of the class name.

Therefore, using the definition just given, urlhtp: // host / webappprefix / servlet / test

Can be used as

http://host/webappprefix/servlet/moreServlets.TestServlet

Site. Keep in mind: XML elements are not only sensitive, but also define their order. For example, all servlet elements in the web-app element must be in all servlet- mapping elements (introduced by the next section), and also discussed in Section 5.6 and 5.11 (if any) prior to. Similarly, servlet-name child elements of servlet must also appear before servlet-class. Section 5.2 "Deployment Descriptor Document" The order of elementality will be described in detail. For example, the program list 5-1 gives a simple servlet called TestServlet, which resides in the MoreServlets package. Because this servlet is part of a web application in a directory called DeployDemo, TestServlet.class is placed in DeployDemo / Web-INF / CLASSES / MORESERVLETS. Program Listing 5-2 gives a part of the web.xml file that will be placed in the deploydedeno / web-INF /. This web.xml file uses servlet-name and servlet-Class elements to associate name Test with TestServlet.class. Figures 5-1 and Figure 5-2 show the results when using the default URL and the registration name call TestServlet, respectively. Listing 5-1 TestServlet.javapackage moreservlets; import java.io *;. Import javax.servlet *;. Import javax.servlet.http *;. / ** Simple servlet 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/.

* © 2002 Marty Hall;. May be 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" " / n" "

URI : " URI " / n " " ");}} Listing 5-2 Web.xml (Description Servlet name)

"> - ... -> test moreservlets.testServlet 3.2 defined custom URL Most servers have a default Servervet URL:

http://host/webapprefix/servlet/packagename.servletname

. Although it is very convenient to use this URL in development, we often want another URL to deploy. For example, a URL that appears in a web application is required (eg Http: // Host / WebAppreFix / Anyname), and there is no servlet item in this URL. The URL located on the top layer simplifies the use of relative URLs. In addition, for many developers, the top URL looks more shorter than the longer and more troublesome default URL. In fact, sometimes you need to use a custom URL. For example, you may want to close the default URL mapping to better enforce secure restrictions or prevent users from accidentally accessing a servlet without initialization parameters. If you prohibit the default URL, how do you access servlet? At this time, only the custom URL is used. To assign a custom URL, servlet-mapping elements can be used and its servlet-name, and url-pattern child elements. The servlet- name element provides an arbitrary name that can be used to reference the corresponding servlet; URL-Pattern describes the URL of the root directory relative to the web application. The value of the URL-Pattern element must be started in a slash (/). Let's give a simple web.xml excerpt, which allows URLHTTP: // Host / WebAppprefix / URLTest

Instead of

http:// host / webapppprefix / servlet / test

Or http: //host/webapprefix/servlet/moreServlets.TestServlet. Note that the XML header, DOCTYPE declaration, and web-app are closed elements. In addition, you can recall, the XML element is not casual. In particular, you need to put all servlet elements before all servlet-mapping elements. test Test / urltest URL mode can also contain wildcards. For example, the following applet indicates that the server sends all the URL prefixed in the web application to start with the request to be named Bashms. Bashms msutils.asptranslator Bashms / *. ASP 3.3 Name JSP page Because the JSP page is converted to sevlet, nature hopes like a servlet Name the JSP page. After all, the JSP page may benefit from the initialization parameters, security settings, or custom URLs, just as ordinary servevet. Although the background of the JSP page is actually a servlet sentence is correct, there is a key suspicion: that is, you don't know the actual class name of the JSP page (because the system chooses this name). Therefore, in order to name the JSP page, the JSP-File element can be replaced with servlet-calss elements, as shown below: test /testpage.jsp Name JSP page The reason is identical to the name of the servlet: that is, in order to provide a name for use with custom settings (such as initialization parameters, and security settings), and so in order to change the activation JSP page. The URL (for example, so that multiple URLs are handled by the same page, or remove the .jsp extension from the URL). However, when setting up initialization parameters, it should be noted that the JSP page is using the JSPinit method, not the initial read of the initialization parameters. For example, a program list 5-3 gives a simple JSP page called TestPage.JSP, which is just printing the local part of the URL used to activate its URL. TestPage.JSP is placed on the top of the deploydemo application. Program List 5-4 gives it to allocate a registered name PageName, then this registration name

Http: // host / webappppppprefix / urltest2 / anything in the form of a URL associated web.xml file (ie, deploydemetero / web-inf / web.xml). Program List 5-3 TestPage.jsp jsp test page </ title> </ head> < Body bgcolor = "# fdf5e6"> <h2> URI: <% = request.getRequesturi ()%> </ h2> </ body> </ html> program list 5-4 Web.xml (Description JSP page named) <? XML Version = "1.0" Encoding = "ISO-8859-1"?> <! Doctype web-appuble "- // sun microsystems, Inc.//dtd web coplication 2.3 // en" "</p> <p>http://java.sun.com/dtd/web-app_2_3.dtd</p> <p>"> <web-app >- ... -> <servlet> <servlet-name> PageName </ servlet-name> <jsp-file> /testpage.jsp </ jsp-file> </ servlet > <! - ... -> <servlet-maping> <servlet-name> PageName </ servlet-name> <url-pattern> / urltest2 / * </ url-pattern> </ servlet-mapping> < One reason for the establishment of custom URLs for Servlet or JSP pages to servlet or JSP page is to register from init (servlet) or JSPinit (JSP page) method Reading initialization parameters. However, the initialization parameters can be used when using custom URL mode or registration name to access the servlet or JSP page, with a default URL</p> <p>http:// host / webappppprefix / servlet / servletname</p> <p>Cannot be used when access. Therefore, you may want to turn off the default URL, so no one will accidentally call the initialization servlet. This process is sometimes referred to as forbidden activator servlet because most of the server has a standard servlet registered with the default servlet URL and activates the default URL application's actual servlet. There are two main methods for prohibiting this default URL: l Remap / servlet / mode in each web application. l Global Close the activator servlet. It is important to note that although rereading / servlet / mode in each web application is more done than thoroughly activating Servlet, re-mapping can be done with a fully portable manner. Instead, the global prohibition activator servlet is completely for specific machines, and the actual server (such as servletexec) does not have such a selection. The following discussion strategy for re-maping / servlet / URL schema for each web application. The details of the global disable activator servlet in Tomcat are provided later. 4.1 Remap / Servlet / URL Mode Forbidden in a specific web application, http: // host / webapppppprefix / servlet /</p> <p>The process of the beginning of the URL is very simple. What you need is to create an error message servlet and turn all match requests to the servlet using the URL-Pattern element discussed by the previous section. As long as you simply use: <url-pattern> / servlet / * </ url-pattern> as a mode in servlet-maping elements. For example, the program list 5-5 gives the SorryServlet servlet (program list 5-6) with all</p> <p>http:// host / webapppprefix / servlet /</p> <p>The beginning of the URL associated with the deployment descriptor file. Program List 5-5 Web.xml (Description JSP page Named Extract) <? XML Version = "1.0" Encoding = "ISO-8859-1"> <! Doctype Web-Appublic "- // Sun Microsystems, Inc. // DTD Web Application 2.3 // en ""</p> <p>http://java.sun.com/dtd/web-app_2_3.dtd</p> <p>"> <web-app >- ... -> <servlet> <servlet-name> sorry </ servlet-name> <servlet-class> moreservlets.sorryservlet </ servlet-class> </ servlet> <! - ... -> <servlet-maping> <servlet-name> sorry </ servlet-name> <url-pattern> / servlet / * </ url-pattern> </ servlet-mapping> <! - ... -> </ web-app> program list 5-6 SorryServlet.javaPackage bervlets; import javax.io. *; import javax.servlet. *; import javax.servlet.http. *; / ** Simple Servlet Used to Give Error Messages to * Users WHO Try To Access Default Servlet Urls * (IE,</p> <p>http:// host / webappppprefix / servlet / servletname</p> <p>* in Web Applications That Have Disabled this * Behavior. * <p> * Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, *</p> <p>http://www.moreservlets.com/.</p> <p>* © 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 <body bgcolor = / "# fdf5e6 /"> / n " " <h2> " Title "</ H2> / n" "sorry, access to servlets by means of / n" "URLS That Begin with / n" "</p> <p>http:// host / webapppprefix / servlet /</p> <p>/ N " " has been disabled./n " " </ BODY> </ HTML> ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);}} 4.2 Global Prohibit Activator: Tomcattomcat 4 is used to close the default URL is very different from Tomcat 3. The two methods are introduced below: 1. Prohibit Activator: Tomcat 4Tomcat 4 Use the same way as the previous way to close The activator servlet is turned off with the URL-MAPPING element in Web.xml. Differently in Tomcat uses a server-specific global web.xml file dedicated in install_dir / confation, and the previous use is stored every Standard web.xml file in a web-inf directory of a web application. So, in order to close the activator servlet in Tomcat 4, simply comment out / servlet / * URL mapping items in install_dir / conf / web.xml That is, as shown below: <! - <servlet-maping> <servlet-name> invoker </ servlet-name> <url-pattern> / servlet / * </ url-pattern> </ servlet-maping> -> Remind again, it should be noted that this item is located in a Web.xml file stored in the Tomcat stored in install_dir / confation. This file is not standard Web.xml.2 stored in the web-inf directory of each web application. Proactive activator: Tomcat3 In the Apache Tomcat version 3, the InvokerInterceptor item is prohibited by commented in INSTALL_DIR / CONF / Server.xml, for example, the following is the server.xml file for the default servlet URL. Part. <! - <rel ketinterceptor classname = "org.apache.tomcat.Request.invokerinterceptor" debug = "0" prefix = "/ servlet /" /> -> 5 initialization and preload S ERVLET and JSP page discuss the method of controlling the startup behavior of the Servlet and JSP pages. In particular, explain how to assign initialization parameters and how to change the time to load the Servlet and JSP pages in the server life. 5.1 Assigning Servlet Initialization Parameters Using the init-param element to provide initialization parameters to servlet, the init-param element has param-name and param-value child elements. For example, in the following example, if the INITSERVLET servlet is accessible using its registration name (INITTEST), it will be able to call GetServletConfig () from its method, get "Value 1", call GetServletConfig ) .GetinitParameter ("param2") gets "2".</p> <p><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> A few things to note when involving initialization parameters: L returns the value. The return value of GetInitParameter is always a string. Therefore, in the previous example, INT can be obtained using INTEGER.PARSEINT for PARAM2. l In the JSP in JSP. The JSP page uses JSPinit instead of init. The JSP page also needs to use the JSP-File element instead of servlet-class. l Default URL. The initialization parameters can be used only when accessing the servlet through custom URL schema related to their registration names or custom URL schema. Therefore, in this example, PARAM1 and PARAM2 initialization parameters will be available in URLHTTP: // Host / WebAppprefix / Servlet / InitTest</p> <p>It is available, but in use URL</p> <p>http://host/webappprefix/servlet/mypackage.initservlet</p> <p>Can not be used. For example, program list 5-7 gives a simple servlet called INITSERVLET, which uses the init method to set the firstname and emaildress fields. Program Listing 5-8 gives the allocated name inittest to the Web.xml file for servlet. Listing 5-7 InitServlet.javapackage 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, *</p> <p>http://www.moreservlets.com/.</p> <p>* © 2002 Marty Hall;. May be 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.HEADWITHTILE ("init servlet" "<body bgcolor = /" # fdf5e6 / "> / n" "<h2> init parameters: </ h2> / n " " <Ul> / n " " <li> first name: " firstname " / n " " <li> email address: " EmailAddress " / n " " </ ul> / n " "</ Body> </ html>");}}} program list 5-8 Web.xml (Description Extract of the initialization parameters) <? XML Version = "1.0" eNCoding = "ISO-8859-1?> <> < ! DOCTYPE Web-App Reproduic "- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En" "http://java.sun.com/dtd/web-app_2_3.dtd</p> <p>"> <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></p> <p>Ellison@microsoft.com</p> <p></ param-value> </ init-param> </ servlet> <! - ... -> </ web-app> 5.2 Allocation JSP Initialization Parameters Provide initialization parameters to the JSP page differ from three aspects Servlet provides initialization parameters. 1) Use JSP-File instead of servlet-class. Therefore, the servlet element of the web-inf / web.xml file is shown below: <servlet> <servlet-name> PageName </ servlet-name> <jsp-file> /RealPage.jsp </ jsp-file> <init- Param> <param-name> ... </ param-name> <param-value> ... </ param-value> </ init-param> ... </ servlet> 2) almost always allocated one Clear URL mode. For servlet, usually use http: // host / webapprefix / servlet /</p> <p>The default URL began. Just remember, use the registration name instead of the original name. This is also legal for JSP pages. For example, in the examples given above, available URLs</p> <p>http: // host / webapppprefix / servlet / PageName</p> <p>Accessing RealPage.JSP has access to the initialization parameters. But when used in the JSP page, many users do not like to use the URL of the regular servlet. In addition, if the JSP page is located in the directory for the server to provide a directory list (eg, a directory that is neither index.html does not have an index.jsp file), the user may connect to this JSP page, click it, thus Accidentally activate uninitialized pages. Therefore, a good way is to use the URL-Pattern (5.3) to associate the original URL of the JSP page with the registered servlet name. In this way, the client can use the Normal name of the JSP page, but still activate the customized version. For example, given a servlet definition from item 1, you can use the following servlet-maping definition: <servlet-mapping> <servlet-name> PageName </ servlet-name> <url-pattern> /realpage.jsp </ url- Pattern> </ servlet-mapping> 3) JSP page Use JSPinit instead of init. The INTi method has been automatically established from the JSP page. Therefore, using JSP declarations to provide an init method is illegal, the JSPinit method must be developed. To illustrate the process of initializing the JSP page, the program list 5-9 gives a JSP page named initpage.jsp, which contains a JSPINIT method and placed on the top of the deploydemo web application hierarchy. general,</p> <p>http://host/deploydemo/initpage.jsp</p> <p>The form of URL will activate the version of this page does not have an initialization parameter access, thereby displays NULL for the firstName and EmailAddress variables. However, the web.xml file (Program List 5-10) assigns a registration name and then associates the registration name with the URL mode / ITPAGE.JSP. Program List 5-9 INTPAGE.Jsp <! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // en"> <html> <head> <title> jsp init test </ title> </ head> < Body BGColor = "# fdf5e6"> <h2> init parameters: </ h2> <ul> <li> first name: <% = firstname%> <li> email address: <% = emaildress%> </ ul> < / BODY> </ HTML> <% private String firstName, emailAddress;! public void jspInit () {ServletConfig config = getServletConfig (); firstName = config.getInitParameter ( "firstName"); emailAddress = config.getInitParameter ( "emailAddress") ;}%> Program List 5-10 Web.xml (Description JSP page of the init parameter excerpt) <? XML Version = "1.0" encoding = "ISO-8859-1"?> <! Doctype web-Appublic "- / / Sun microsystems, Inc.//dtd Web Application 2.3 // en "" http://java.sun.com/dtd/web-app_2_3.dtd</p> <p>"> <web-app >- ... -> <servlet> <servlet-name> initpage </ servlet-name> <jsp-file> /initpage.jsp </ jsp-file> <init- Param> <param-name> firstname </ param-name> <param-value> Bill </ param-value> </ init-param> <init-param> <param-name> emaildRESS </ param-name> < PARAM-VALUE></p> <p>Gates@oracle.com</p> <p></ param-value> </ init-param> </ servlet> <! - ... -> <servlet-mapping> <servlet-name> initpage </ servlet-name> <url-pattern> / initpage .jsp </ url-pattern> </ servlet-maping> <! -> </ web-app> 5.3 Provides initialization parameters within the application range, allocating initialization parameters for a single servlet or JSP page . The specified servlet or JSP page reads these parameters with the GetItParameter method of ServletConfig. However, in some cases, it is desirable to provide initialization parameters within the system ranges that can be read by the GetInitParameter method of servletContext with servletContext. The initialization value within these systems can be declared using the context-param element. Context-param elements should include param-name, param-value, and optional Description sub-elements, as shown below: <context-param> <parame> Support-email </ param-name> <param-value> Blackhole @ mycompany.com</p> <p></ param-value> </ context-param> Recalls, in order to ensure portability, the elements within Web.xml must be declared in the correct order. However, it should be noted here that the context-param element must arbitrarily arbitrarily after Icon, Display-Name or Description, and Filter, Filter-Mapping, Listener or Servlet elements. 5.4 Loading a servlet if the server is started, such as a servlet or JSP page has an init (servlet) or JSPinit (JSP) method for a long time. For example, if the init or jspinit method looks out from a database or resourcebundle. In this case, the default behavior of loading the servlet when the first client request will generate a longer period of time for the first client. Therefore, it is possible to use the servlet's Load-On-Startup element specify that the server loads the servlet during the first start. Below is an example. <servlet> <servlet-name> ... </ servlet-name> <servlet-class> ... </ servlet-class> <! - or jsp-file -> <load-on-startup /> </ servlet> You can provide an integer to this element instead of using an empty load-on-startup. Ideas is that the server should load a small number of servlets or JSP pages before loading larger number of servlets or JSP pages. For example, the following servlet item (WEB-APP element in the web-app element placed in the web-inf directory of the web application) will indicate the server first load and initialize the searchServlet, then load and initialize the result directory located in the web application. The servlet generated in the index.jsp file. <servlet> <servlet-name> search </ servlet-name> <servlet-class> mypackage.searchServlet </ servlet-class> <! - or jsp-file -> <load-on-startup> 1 </ Load-on-startup> </ servlet> <servlet> <servlet-name> results </ servlet-name> <servlet-class> /Results/index.jsp </ servlet-class> <! - or jsp-file -> <load-on-startup> 2 </ load-on-startup> </ servlet> 6 Declaration Filter Servlet version 2.3 introduces the concept of the filter. Although all servers supporting Servlet API version 2.3 support filters, in order to use elements related to the filter, the DTD must be used in Web.xml. The filter can be intercepted and modified to enter a request for a servlet or a JSP page or from a servlet or JSP page. Before performing a servlet or JSP page, the DOFILTER method of the first correlation filter must be performed. When the filter is called DOFILTER, the next filter in the chain is called for its FilterChain object. If there is no other filter, a servlet or a JSP page is executed. The filter has all access to the arrival of the servletRequest object, so they can view the client name and find the cookie.</p> <p>In order to access the output of the Servlet or JSP page, the filter can wrap the response object in a stand-in object, and the output is accumulated to a buffer. After calling the Dofilter method of the FilterChain object, the filter checks the buffer. If necessary, it is modified, then transferred to the client. For example, a program list 5-11 empire is difficult to have a simple filter, just access the relevant servlet or JSP page, it intercepts the request and prints a report on the standard output (most of the development process is running on the desktop system, most This filter can be used by the server). Program List 5-11 ReportFilter.javaPackage MoreServlets; import java.io. *; Import javax.servlet. *; Import javax.servlet.http. *; Import java.util. *; / ** SIMPLE FILTER THATS A Report on . the standard output * whenever the associated servlet or JSP page is accessed * <P> * Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http: //www.moreservlets.com/.</p> <p>* © 2002 Marty Hall; may be freely used or adapted * / public class ReportFilter implements Filter {public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {HttpServletRequest req = (HttpServletRequest) request;. System.out .println (Req.getRemoteHost () "Tried to Access" Req.GetRequestURL () "On" new date () "."); chain.dofilter (Request, response);} public void init (FilterConfig CONFIG) THROWS servletexception {} PUBLIC VOID Destroy () {} Once a filter is established, you can use the filter element and filter-name, file-class (fully qualified class name) in Web.xml. (Optional) INIT-Params sub-elements declare it. Please note that the order of the elements appear in the web-app element of Web.xml is not arbitrary; allowing the server (but not required) to force the desired order, and some of the actual servers do this. But here you should pay attention, all Filter elements must appear before any Filter-Mapping element, the filter-mapping element must appear before all servlets or servlet-mapping elements. For example, given the above ReportFilter class, the following Filter declaration can be made in Web.xml. It is associated with the actual class REPORTFILTER (in the MoreServlets package). <Filter> <filter-name> reporter </ filter-name> <filter-class> Morevlets.Reportfilter </ filter-class> </ filter> Once a filter is named, use the filter-mapping element to put it with one Or multiple servlets or JSP pages are associated. There are two options on this work. First, use the filter-name and servlet-name child elements to use a specific servlet name (this servlet name must be declared in the same web.xml file later). For example, the following program clip indicates that the system runs a filter named Reporter as long as a custom URL accesses the servlet or JSP page named SomeServletName. <filter-mapping> <filter-name> reporter </ filter-name> <servlet-name> SomeServletName </ servlet-name> </ filter-maping> Second, the filter-name and url-pattern child elements will be filtered The device is associated with a set of servlets, JSP pages, or static contents. For example, a phase of the program segment indicates that the system runs a filter named Reporter as long as any URL in the web application is accessed.</p> <p><filter-mapping> <filter-name> reporter </ filter-name> <url-pattern> / * </ url-pattern> </ filter-maping>, for example, program list 5-12 gives a ReportFilter filter Part of the Web.xml file associated with the servlet called PageName. The name PageName is associated with a JSP page called TestPage.jsp and the URL at which the mode http: // Host / WebAppreFix / URLTEST2 / start is associated. TestPage.JSP Sourcecodes have been discussed in the JSP page to be named in the previous 3 "assignment name and custom URL". In fact, the Servlet and Servlet-Name item in the program list 5-12 are unworthy from the festival. These web.xml items are given to see the debug report in the following standard output form (the wrap is for easy reading). Audit.irs.gov Tried to AccessHttp: //mycompany.com/deploydemo/urltest2/business/tax-plan.html</p> <p>On Tue Dec 25 13:12:29 Edt 2001. Program List 5-12 Web.xml (Description Filter Usage) <? XML Version = "1.0" eNCoding = "ISO-8859-1?> <! doctype Web -Apppublic "- // Sun microsystems, Inc.//dtd Web Application 2.3 // en" "</p> <p>http://java.sun.com/dtd/web-app_2_3.dtd</p> <p>"> <web-app> <filter> <filter-name> reporter </ filter-name> <filter-class> moreesevlets.reportfilter </ filter-class> </ filter> <! - ... -> <filter-mapping> <filter-name> reporter </ filter-name> <servlet-name> PageName </ servlet-name> </ filter-maping> <! - ... -> <servlet> <servlet -Name> PageName </ servlet-name> <jsp-file> /Realpage.jsp </ jsp-file> </ servlet> <! - ... -> <servlet-maping> <servlet-name> PageName </ servlet-name> <url-pattern> / urltest2 / * </ url-pattern> </ servlet-maping> <! - ... -> </ web-app> 7 Specify welcome page If users provide What happens like http: // host / webappppprefix / directoryname / like a directory name but does not contain file names, what happens? Can users get a directory table? One error? Or standard file content? If Get the contents of the standard file, is index.html, index.jsp, default.html, default.htm or something else? Welcome-file-list element and its assistive Welcome-File elements solve this blurred problem. For example, The following Web.xml item pointed out that if a URL gives a directory name but does not give the file name, the server should try index.jsp, then try index.html. If both are not found, the result is dependent Servers (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, it is not necessarily the case. Therefore, it is a good habit to ensure that portability is a good habit. 8 Specify the error page. Now I know, you never make mistakes when developing a Servlet and JSP pages, and all of your pages are clear, and the general programmers will not be confused by them. However, it will always make mistakes, and users may provide non-specified parameters, using incorrect URLs or not provide the necessary form field values. In addition, other developers may not be so careful, they should have some tools to overcome their shortcomings. Error-Page element is used to overcome these problems. It has two possible child elements, namely error-code and exception- type. The first child element error-code indicates the URL used during a given HTTP error code. The second child element ExcPETITION-TYPE indicates that the URL used in the appearance of a given Java but does not capture.</p> <p>Error-Code and Exception-Type use the Location element to indicate the corresponding URL. This URL must start. The page pointed out at the location indicated by the HTTPSERVLETREQUEST object can access information about the error, which two attributes are: javax.servlet.error.Status_code and javax.servlet.error.MESSAGE. Memories can be memo that the child elements of the web-app are declared in the correct order in Web.xml. As long as you remember, Error-Page appears near the end of the web.xml file, the servlet, servlet-name, and Welcome-file-List can be. 8.1 Error-Code Element In order to better understand the value of the error-code element, consider if the file name is incorrect, most sites will reflect. Doing so generally a 404 error message, it means that it cannot be found, but there is almost no more useful information. On the other hand, you can try it at www.microsoft.com</p> <p>,</p> <p>Www.ibm.com</p> <p>Position or especially</p> <p>Www.bea.com</p> <p>Output unknown file names. This is a useful message that provides a selectable location in order to find the page of interest. Providing such useful error pages for web applications is worth it. In fact, RM-Error-Page Child Elements). The HTML form given by Form-Login-Page must have a J_Security_Check's action property, a username text field named J_USERNAME and a password field named J_Password. For example, program list 5-19 indicates that the server uses a form-based verification. A page named login.jsp in the top of the web application will collect usernames and passwords, and the failed login will be reported by the page of login-error.jsp in the same directory. Program List 5-19 Web.xml (Description Login-Config) <? XML Version = "1.0" Encoding = "ISO-8859-1"> <! Doctype web-appublic "- // Sun Microsystems, Inc. // DTD Web Application 2.3 // en ""</p> <p>http://java.sun.com/dtd/web-app_2_3.dtd</p> <p>"> <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 Limiting access to web resources Now, you can indicate what verification method for the server use. "God," You said "Unless I can specify a URL to receive the protected URL, there is not much place. "Yes. Point out these URLs and explain what protocat that they should protect is the use of the security-constriaint element. This element should appear in front of the login-config in web.xml. It contains a possible child element, respectively YES: 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 that should be protected. All Security-Constraint elements At least one Web-Resource-Collection item must be included. This element is given a web-resource-name element that gives an arbitrary identifier name, a URL-Pattern element that determines the URL that should be protected, and a http command that is applied to this protection ( Get, Post, etc. All documents in the catalog should be protected. <Security-constraint> <web-resource-coolection> <web-resource-name> proPrietary </ web-resource-name> <url-pattern> / propritary / * </ url-pattern > </ Web-Resource-Coolection> <! - ... -> The important thing should be noted that URL-Pattern applies only to clients directly accessing these resources. Especially, it Not suitable for use with RequestDispatcher to access the page, or not suitable for the page similar to JSP: Forward, this uniformity is good if you use the appropriate words. For example, servlet can utilize the MVC architecture Find data, put it in the bean, send the request to extract data from the bean and display it. We hope that the protected JSP page is never directly accessed, but only BEAN's servlet will be used by establishing this page To access it .url-pattern and auth-contraint elements can be directly visited by the declaration Ask the JSP page to provide this guarantee. However, this uniform behavior may allow developers to relax and make them chance to provide unrestricted access to protected resources.</p> <p>l Auth-constraint Although the web-resource-cololion element has been protected, the Auth-Constraint element indicates which users should have access to protected resources. This element should include one or more user category Role-Name elements that have access rights, and the Description element that contains (optional) a descriptive role. For example, the Security-Constraint element department in Web.XML specifies only access to the specified resource only by specifying an Administrator or Big Kahuna (or both). <security-constraint> <Web-resource-cool> ... </ web-resource-cool> <auth-constraint> <role-name> administrator </ role-name> <role-name> kahuna </ role- Name> </ auth-constraint> </ security-constraint> It is important to recognize that this process is over. How does the server determine which users are in any role and how it stores the user's password, which is fully dependent on a specific system. For example, Tomcat uses install_dir / conf / Tomcat-users.xml to associate the username with the role name and password, as shown in the following example, indicating that the user Joe (Password Bigshot) and Jane (password ENAJ) belong to Administrator and Kahuna roles. <Tomcat-Users> <user name = "joe" password = "bigshot" roles = "administrator, kahuna" /> <user name = "jane" password = "enaj" roles = "kahuna" /> </ tomcat-user > l User-data-constraint This optional element indicates that any transport layer protection is used when accessing the relevant resource. It must contain a Transport-Guarantee sub-element (legal value is None, Integral or Confidential), and optionally contains a Description element. Transport-Guarantee will not restrict the communication protocol used for the NONE value. The IntegRal value indicates that the data must be transferred in a manner that prevents people from intercepting it. Although the principle (and in the future HTTP version), there may be differences between Integral and Confidential, but in the current practice, they just simply require SSL. For example, the following indicates that the server only allows HTTPS connections to the relevant resources: <security-constraint> <! -> <user-data-constraint> <transport-guarance> confidential </ transport-guarance> </ User-data-constraint> <This rarely used sub-elements of DISPLAY-NAMESECURITY-CONSTRAINT gives a name that may be used by the GUI tool.</p> <p>9.3 Distribution Role Name So far, discussing the security issues that have been set to be completely processed by the container (server). But the servlet and the JSP page can also handle their own security issues. For example, the container may allow users to access a page that displays an additional close to the executive person from a BigWig or Bigchese role, but only the BigWig user is allowed to modify the parameters of this page. One common way to accomplish this more detailed control is to call the HTTPServletRequset's ISUSERINROLE method and modify the access. Servlet's security-role-ref child elements provide an alias that appears in the server's dedicated password file. For example, if a servlet called Request.isuserinRole ("Boss") is written, then the servlet is used in a server that calls role Manager Manager instead of BOSS. The following block allows the servlet to use any of these 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 all security roles that will appear in the Role-Name element. A global list. The life role makes advanced IDE easy to handle security information. 10 Controlling the session timeout If a session is not accessed within a certain period of time, the server can throw it away to save memory. You can use the HTTPSession's SetMaxInactiveInterval method to 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 utilized to give a clear timeout value for all servers. The unit of timeout is minute, so the following example sets the default session timeout value of three hours (180 minutes). <session-config> <session-timeout> 180 </ session-timeout> </ session-config> 11 Web application's documentation is 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 (Write this article, has been acquired by Macromedia) and IBM Visuaage for Java. A large number of web.xml elements are not only designed for servers, but also designed to develop environment. They include Icon, Display-Name, and Discription. Memories can be recalled in Web.xml to declare the web-app child element in the appropriate order. However, just remember that Icon, Display-Name and Description are the first three legal elements within the web-app elements of web.xml. l iConicon elements indicate a GUI tool to represent one and two image files that represent the web application. A 16 x 16 GIF or JPEG image can be specified using the Small-ICON element, specifying an image of 32 x 32 with the Large-ICON element.</p> <p>Let's take an example: <icon> <small-icon> /Images/small-book.gif </ small-icon> <large-icon> /images/tome.jpg </ large-icon> </ icon> l display -namedisplay-name element provides a GUI tool that may be used to mark a name for this web application. Here is an example. <Display-name> Rare Books </ display-name> l descriptiondescription element provides explanatory text, as shown below: <description> This Web application represents the store developed forrare-books.com, an online bookstore specializing in rareand limited-edition Books. </ description> 12 Association and MIME Type Server generally have a method that allows Web site administrators to associate file extensions to media. For example, an image / jpeg MIME type named Mom.jpg will be automatically given. However, if your web app has several unusual files, you want to ensure that they are assigned to a MIME type when sending to the client. MIME-MAPPING Elements (with Extension and MIME-TYPE sub-elements) provide this guarantee. For example, the following code indicates that the server assigns 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-maping> perhaps, your web application wants to override the standard mapping . For example, the following code will tell the server to specify the .ps file as plain text when sending to the client as a plain text rather than the PostScript (Application / PostScript). <mime-mapping> <extension> PS </ extension> <mime-type> application / postscript </ mime-type> </ mime-maping> 13 Location TLDJSP TAGLIB element has a necessary URI property, which gives a TLD (Tag Library Descriptor) file is relative to the root of the web application. The actual name of the TLD file may change when publishing a new label library version, but we want to avoid changing all existing JSP pages. In addition, it is possible to also want to use a short URI that keeps a Taglib element. This is the Taglib element distribution field for deploying the descriptor file. Taglib contains two sub-elements: taglib-uri and taglib-location. Taglib-URI elements should match something for the URI attribute used for JSP taglib elements. The Taglib-Location element gives 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, if Web.xml contains the following contents within a web-app element.</p> <p><taglib> <taglib-uri> /charts.tld </ taglib-uri> <taglib-location> /web-inf/tlds/chart-tags-1.3beta.tld </ taglib-location> </ taglib> given After this statement, the JSP page can use the label library by the following simplified form. <% @ Taglib Uri = "/ Charts.TLD" prefix = "someprefix"%> 14 Specifying Application Event Listening Programs Application Event Listener Program is a class that is notified or modified when a servlet environment or session object. They are new content in version 2.3 of the Servlet specification. Here is only the usage of web.xml to register a listener to the web app to the web application. Registering a listener involves placing a Listener element within the web-app element of Web.xml. In the Listener element, the Listener-Class element lists the complete qualified class name of the listener, as shown below: <listener> <listener-class> package.listenerclass </ listener-class> </ listener> Although the structure of the Listener element Very simple, but please don't forget, you must correctly give the order of sub-elements within the web-app element. Listener elements are located before all Servlet elements and all filter-mapping elements. In addition, because the application life listener is a version 2.3 version of the Server Victor Victor, you must use the version 2.3 version of Web.xml DTD, not 2.2. For example, program list 5-20 gives a simple listener called ContextRext, as long as the servlet-context of the web application (such as load web application) or elimination (such as server is turned off), it displays a standard output news. Program List 5-21 gives a part of the web.xml file required for this listener registration. Listing 5-20 ContextReporterjavapackage 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 JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/.</p> <p>* © 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 () ".");}} Listing 5-21 Web.xml (declare an excerpt of a listener) <? XML Version = "1.0" Encoding = "ISO-8859-1"> <! doctype web-appuble "- // sun microsystems, incaps//dtd web application 2.3 // en" "http: // java .sun.com / DTD / Web-App_2_3.dtd</p> <p>"> <web-app >- ... -> <filter-maping> ... </ filter-mapping> <listener> <listener-class> package.listenerclass </ listener-class> </ listener> <servlet> ... </ servlet> <! - ... -> </ web-app> 15 J2EE Element This section describes the web.xml element for web applications for the J2EE environment components. Here A concise introduction, please refer to the details</p> <p>http://java.sun.com/j2ee/j2ee-1_3-fr-spec.pdf</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-132532.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="132532" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.040</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '9PfnhMUqE7srLZ7r8gPt_2FQEfLNAXKAckgBGpKlYWEkYMjLHjGfsAAaCmxq2j3NsBd6vWgY7b6f3b0rCHUrx5tw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>