Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Servlet url mappings in web.xml used?

Tags:

People also ask

What is the use of servlet mapping in web xml?

Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.

What is URL pattern in web XML file?

The url-pattern element of a servlet-mapping or a filter-mapping associates a filter or servlet with a set of URLs. When a request arrives, the container uses a simple procedure for matching the URL in the request with a url-pattern in the web. xml file.

Which tag is used to define the URL of servlet?

servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called.


I have a web.xml file with content:

<servlet>     <servlet-name>servlet1</servlet-name>     <servlet-class>org.mycompany.test1</servlet-class> </servlet> <servlet>     <servlet-name>servlet2</servlet-name>     <servlet-class>org.mycompany.test2</servlet-class> </servlet> <servlet-mapping>     <servlet-name>servlet1</servlet-name>     <url-pattern>/path/test</url-pattern> </servlet-mapping> <servlet-mapping>     <servlet-name>servlet2</servlet-name>     <url-pattern>/path/test/*</url-pattern> </servlet-mapping> 

I tried requests

.../path/test/abc  .../path/test 

Both requests are processed by Servlet2. Why?

UPDATE

Thank you guys for your help. I realised that behaviour depends on order of servlet-mapping declaration. I tried this web.xml

<servlet>     <servlet-name>servlet1</servlet-name>     <servlet-class>org.mycompany.test1</servlet-class> </servlet> <servlet>     <servlet-name>servlet2</servlet-name>     <servlet-class>org.mycompany.test2</servlet-class> </servlet> <servlet>     <servlet-name>servlet3</servlet-name>     <servlet-class>org.mycompany.test3</servlet-class> </servlet> <servlet>     <servlet-name>servlet4</servlet-name>     <servlet-class>org.mycompany.test4</servlet-class> </servlet>  <servlet-mapping>     <servlet-name>servlet1</servlet-name>     <url-pattern>/path/test</url-pattern> </servlet-mapping> <servlet-mapping>     <servlet-name>servlet2</servlet-name>     <url-pattern>/path/test/*</url-pattern> </servlet-mapping> <servlet-mapping>     <servlet-name>servlet3</servlet-name>     <url-pattern>/path/*</url-pattern> </servlet-mapping> <servlet-mapping>     <servlet-name>servlet4</servlet-name>     <url-pattern>/path</url-pattern> </servlet-mapping> 

results:

.../path/test/abc - servlet2 .../path/test/ - servlet2 .../path/test - servlet2  .../path/abc - servlet3 .../path/ - servlet4 .../path - servlet4