Web. Xml detailed

Source: Internet
Author: User
Tags null null

The role of Web. xml

Web. XML, the most important configuration file in a Tomcat project. Web. XML does not actually----as long as you are sure that you do not need any filters, listeners, Servlets, etc. in your project. I tried, without web. XML for JSP pages that have been compiled into servlets without affecting the normal display, but those JSP pages that are not compiled into Servlets will be reported with a 500 error when accessed. Here is a look at the role of commonly used tags in Web. Xml.

Welcome-file-list

This tag is used to configure the home page:

<welcome-file-list>    <welcome-file>index1.jsp</welcome-file>    <welcome-file> index2.jsp</welcome-file>    <welcome-file>index3.jsp</welcome-file>    <welcome-file >index4.jsp</welcome-file>    <welcome-file>/target/redirectandfoward.jsp</welcome-file ></welcome-file-list>

This configuration means that when a user accesses the http://ip:port/project name , the page is searched from the root of the project, based on the list of welcome-file-list configured pages:

1, the first configuration of the index1.jsp can be found, on display index1.jsp

2, can not find index1.jsp, then to find a second index2.jsp,index2.jsp to find on the display index2.jsp,

3, can not find index3.jsp, then go to find the third index3.jsp, and so on, if all the pages are not found the report HTTP Status 404 that page Cannot find

Note that, like the last Welcome-file configuration is also supported, I tried the front of the "/" can be added without

Error-page

Error-page indicates that when HTTP returns the specified status code, the container forwards the request to the specified page of the configuration:

<error-page>    <error-code>400</error-code>    <location>/filter/error.jsp</ location></error-page>  <error-page>    <error-code>404</error-code>    < location>/filter/error.jsp</location></error-page>  <error-page>    <error-code >500</error-code>    <location>/filter/error.jsp</location></error-page>

This means that the HTTP status code is 400, 404, 500, the request will be forwarded to the http://ip:port/project name/filter/error.jsp this page up. Note that this is error-code, so if it's 200, it's ineffective.

Filter

Filter does not say, the two include methods and filter in the dispatcher analysis of the article has been very detailed, the filter is written in the above.

Also note that, in fact, we all know, mention: Walk the filter is the order of the filter definition

Servlet

Servlet developers are more familiar with matching rules before matching the path to the corresponding servlet class, not to mention. The following is a relatively less commonly used, only relative, this servlet is very common in the wording:

<servlet>    <servlet-name>startUpServlet</servlet-name>    <servlet-class> com.xrq.servlet.startupservlet</servlet-class>    <init-param>        <param-name> name</param-name>        <param-value>123</param-value>    </init-param>    < init-param>        <param-name>Age</param-name>        <param-value>456</param-value>    </init-param>    <load-on-startup>8</load-on-startup></servlet>

This is a startup servlet, which indicates that the servlet starts when the container starts, calls its init () method, so first the first label Load-on-start, points to say:

1. The Load-on-startup element marks whether the container is loading the servlet at startup (instantiating and invoking its Init method)

2, its value must be an integer indicating the order in which the servlet should be loaded

3. A value of 0 or greater than 0 o'clock indicates that the container loads and initializes the servlet when the application starts

4, when the value is less than 0 or unspecified, indicates that the container will not load when the servlet is selected

5, the lower the positive value, the higher the priority of the servlet, the first time the application starts to load

6, the value of the same time, the container to choose the order to load

So, when a positive integer greater than or equal to 0 is configured in the Load-on-startup, the servlet can be used as a normal servlet, but it will be loaded with the init () method when the servlet is started.

The other one is Init-param, indicating a key value pair, can only be used in this servlet, obtained through ServletConfig, Startupservlet is:

 Public classStartupservletextendshttpservlet{/*** Serialization*/    Private Static Final LongSerialversionuid = 1L;  Public voidInit ()throwsservletexception {System.out.println ("Startupservlet.init ()"); System.out.println ("Name:" + getservletconfig (). Getinitparameter ("name")); System.out.println (' Age: ' + getservletconfig (). Getinitparameter ("Age")); }        protected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {} Public voiddestroy () {System.out.println ("Startupservlet.destory ()"); }}

Servlets can only be configured within their own <servlet> tags <init-param>

Listener

Listener is the listener, the listener of the servlet, it can listen to the client's request, server-side operations, and so on before and after the event to do some necessary processing. Through the listener, you can automatically trigger some actions, such as listening to the number of online users, the following is a listener to listen to the number of users, first, the Web. XML configuration is simple:

<listener>    <listener-class>com.xrq.listener.usercounterlistener</listener-  Class></listener>

Write a listener, listening to the number of users is generally based on session creation and session invalidation, so the implementation of Httpsessionlistener:

 Public classUsercounterlistenerImplementshttpsessionlistener{PrivateAtomicinteger ai =NewAtomicinteger (0);  Public voidsessioncreated (httpsessionevent se) {ai.incrementandget (); }         Public voidsessiondestroyed (httpsessionevent se) {ai.decrementandget (); }         Public intGetusercount () {returnAi.get (); }}

In addition to listening to the listener of the session, we introduce some other listener interfaces:

1, Servletcontextlistener

Used to listen for Web reference startup and destruction events, Sevletcontextlistener is ServletContext listener, if servletcontext changes, such as server startup, server shutdown, Will be heard by the Servletcontextlistener supervisor. Listener event is servletcontextevent

2, Servletcontextattributelistener

The event used to listen for Web App property changes, including adding properties, deleting attributes, and modifying properties. Listening Time is servletcontextattributeevent

3, Httpsessionbindinglistener

Httpsessionbindinglistener is the only listener that does not need to be configured in Web. XML, when our class implements the Httpsessionbindlistener interface, as long as the object is added to the session or removed from the session, the container will be divided Do not automatically invoke the following two methods:

(1) void Valuebound (Httpsesssionbindevent event)

(2) void Valueunbound (Httpsessionbindingevent event)

Note that the trigger for this listener is for the class that implements the listener, and only the class that implements the listener is set to the session or removed from the session to trigger the listener

4, Httpsessionattributelistener

An action to listen for a property in the HttpSession, triggering the attributeadded (httpsessionbindevent se) method when a property is added to the session, and when a property is deleted in the session, Triggers the attributeremoved (httpsessionbindevent se) method, which triggers the attributereplaced (httpsessionbindingevent se) method when the session property is reset.

Note that the trigger for this listener is for all sessions, as long as the session's properties change, this listener will be triggered

5, Httpsessionlistener

This has already been written, monitoring httpsession. The sessioncreated (httpsessionevent se) method is triggered when a session is created, and the sessiondestoryed (httpsessionevent se) method is triggered when a session is destroyed

6, Httpsessionactivationlistener

This is not used much, mainly listening to the same session transferred to a different JVM situation

7, Servletrequestlistener and Servletrequestattributelistener

Similar to Servletcontextlistener and Servletcontextattributelistener, the former listens for the creation and destruction of request, and the latter listens for additions and deletions of attributes in request

Context-param

The key-value pairs configured in the Context-param are globally shared, and the entire Web project can fetch this context, for example, I have an HTTP port and an HTTPS port configured in XML:

<context-param>    <param-name>NotSSLPort</param-name>    <param-value>8080</ Param-value></context-param><context-param>    <param-name>SSLPort</param-name>    <param-value>8443</param-value></context-param>

The servlet can take this:

protected void DoPost (httpservletrequest request, httpservletresponse response)         throws servletexception, ioexception{    System.out.println ("notsslport:" + getservletcontext (). Getinitparameter ("Notsslport"));    System.out.println ("sslport:" + getservletcontext (). Getinitparameter ("Sslport"));}

Filter can take this:

 Public void DoFilter (servletrequest request, servletresponse response,        throws  IOException, servletexception{    = (httpservletrequest) request;     = req.getsession (). Getservletcontext ();    System.out.println ("notsslport:" + sc.getinitparameter ("Notsslport"));    System.out.println ("sslport:" + sc.getinitparameter ("Sslport"));    Chain.dofilter (request, response);}

Listener can take this, take Servletcontextlistener as an example:

 Public void contextinitialized (Servletcontextevent sce) {    System.out.println ("Enter Sclistener.contextinitialized ");    System.out.println ("notsslport:" + sce.getservletcontext (). Getinitparameter ("Notsslport"));    System.out.println ("sslport:" + sce.getservletcontext (). Getinitparameter ("Sslport"));}

The ultimate goal, anyway, is to take a servletcontext. Does it feel servletcontext familiar? Yes, look at the JSP default built-in object, open a JSP page converted to a servlet, there are built-in object definition:

 null NULL NULL NULL NULL   This  nullnull;

ServletContext is what we often call application

<mime-mapping>

<mime-mapping> may not be very common, this tag is used to specify the corresponding format of the browser processing mode, add Mime-type mapping, you can avoid some types of files directly in the browser opened.

As an example:

<mime-mapping>    <extension>doc</extension>    <mime-type>application/msword</ mime-type></mime-mapping><mime-mapping>    <extension>pdf</extension>    < Mime-type>application/pdf</mime-type></mime-mapping><mime-mapping>    <extension> Rar</extension>    <mime-type>application/x-rar-compressed</mime-type></mime-mapping> <mime-mapping>    <extension>txt</extension>    <mime-type>text/plain</mime-type ></mime-mapping><mime-mapping>    <extension>xls</extension>    <mime-type> Application/vnd.ms-excel</mime-type></mime-mapping>

This specifies how to open five types of files, such as. doc, PDF, rar, TXT, xls. The common MIME types are:

Type Suffix MIME type
Hypertext Markup Language text . htm,. html Text/html
Normal text . txt Text/plain
RFT text . rtf Application/rtf
GIF graphics . gif Image/gif
JPEG graphics . jpg,. jpeg Image/jpeg
Au sound file . au Audio/basic
MIDI music files . Mid,. MIDI Audio/midi, Audio/x-midi
RealAudio Music files . RA,. Ram Audio/x-pn-realaudio
MPEG files . mpg,. mpeg Video/mpeg
AVI file . avi Video/x-msvideo
gzip file . gz Application/x-gzip
Tar file . tar Application/x-tar

Session-config

Session-config is used to configure the session expiration time because there is only one sub-tag in the Session-config:

<session-config>    <session-timeout>30</session-timeout></session-config>

is measured in minutes. Of course, the code can also be set:

"Request.getSession.setMaxInactiveInterval (30 * 60);" Yes, the unit is seconds.

Element load Order

First, it is certain that the loading order is independent of their order in the Web. xml file, that is, the filter is not loaded before the filter is written in listener. The final conclusion is listener->filter->servlet.

The Context-param is then used to provide ServletContext with key-value pairs, that is, application context information, listener, filter, and servlet, which may use the information in those contexts. So should Context-param be written in front of listener, filter, and servlet? Not necessarily, Context-param can be written in any location, so the real load order should be:context-param->listener->filter->servlet.

Web. Xml detailed

Related Article

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.