I have a question according the mapping behaviour.
If there are these mappings given:
<servlet-mapping>
<servlet-name> ServletA </servlet-name>
<url-pattern> *.xml </url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name> ServletB </servlet-name>
<url-pattern> /result/* </url-pattern>
</servlet-mapping>
And there is this HTTP-Request:
/result/example.xml
Which servlet would be mapped and why?
Given your <servlet-mapping> configuration, the request for /result/example.xml would be handled by ServletB because a path match always trumps an extension match.
This is so because an extension match is considered to be a looser (not loser, though that works too :) constraint as it works site-wide when compared to a path match which targets a specific directory and its descendents and is hence more specific in nature.
The matching priority goes like this:
Exact path match
Wildcard path match (a longer match will trump a shorter one)
Extension match
Default servlet (configured with just / to handle all 404s)
I have seen some url-pattern in my xml e.g, in filter-mapping, intercept-url, mvc:resources, etc. Are these patterns always the same ? What's the difference among these URL patterns /, /*, /** ?
It depends in which context you ask this question:
Servlet/Filter mappings
Spring Security mappings
Servlet/Filter mappings
In the Web application deployment descriptor, the following syntax is used to define mappings:
A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for
path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
The empty string ("") is a special URL pattern that exactly maps to the
application's context root, i.e., requests of the form http://host:port/<contextroot>/. In this case the path info is ’/’ and the servlet path and context path is
empty string (““).
A string containing only the ’/’ character indicates the "default" servlet of the
application. In this case the servlet path is the request URI minus the context path
and the path info is null.
All other strings are used for exact matches only
This comes from the Servlet Specification (JSR 315) (section 12.2).
In a Servlet/Filter mapping scenario / means the "default" servlet, normally this is where the DefaultServlet (in Tomcat that is) is mapped to. Basically it handles all incoming requests and doesn't pass them on further down the chain for processing (basically this is the last-catch-all mapping).
/* in the servlet mapping scenario means all incoming URLs (when it cannot be processed it will be handed of the the last-catch-all-mapping).
Spring Security mappings
Now when talking about Spring, /, /* and /** have a different meaning. They refer to so called Ant-style path expressions.
Where / means only / (the root of your application), where /* means the root including one level deep and where /** means everything.
So /foo/* will match a URL with /foo/bar but will not match /foo/bar/baz. Whereas /** or /foo/** would match all of them.
webapps
|
|----helloworld
|
|----WEB-INF
|
|-----classes-HelloWorldServlet.class
|-----lib----servlet-api.jar
|-----web.xml
The above is my directory structure. Now in web.xml i don't know what to give in url-pattern for servlet mapping. What should i give there? Which is the url pattern?
The mechanism for mapping servlets is not relevant to the directory structure, as skaffman noted.
Basically, you have two things in web.xml (regarding servlets):
the <servlet> tag, which defines the alias for the servlet, and its fully-qualified name (for example com.foo.pkg.YourServlet)
the <servlet-mapping> which specifies a url-pattern for a given alias (taken from the <servlet> definitions).
As the name suggest, the url-pattern denotes what URL portion should make the servlet be called. So if you map a given servlet to the url-pattern /myfirstserlet, it will be accessible when the user opens http://localhost:8080/helloword/myfirstservlet, where the first part is the host name and the port, followed by the context name (the name of your webapp), and then the url-pattern
Note: you are currently using the default package (i.e. no package) for your servlet. This is discouraged, so give it some package name. (and put it in WEB-INF/classes/com/foo/pkg/). This is done via specifying package com.foo.pkg;
The familiar code:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My understanding is that /* maps to http://host:port/context/*.
How about /? It sure doesn't map to http://host:port/context root only. In fact, it will accept http://host:port/context/hello, but reject http://host:port/context/hello.jsp.
Can anyone explain how is http://host:port/context/hello mapped?
<url-pattern>/*</url-pattern>
The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().
<url-pattern>/</url-pattern>
The / doesn't override any other servlet. It only replaces the servletcontainer's built in default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's built in default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's built in JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.
<url-pattern></url-pattern>
Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.
Front Controller
In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a built in static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
Map exact URL
Map wildcard paths
Map extensions
Map to the default servlet
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Doesn't match any extensions, next.
Map to the default servlet, return.
To map http://host:port/context/hello.jsp
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Found extension servlet, return.
Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.
false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething
#Controller()
#RequestMapping("/perfix/api/feature")
public class MyController {
#RequestMapping(value = "/doSomething", method = RequestMethod.GET)
#ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base #RequestingMapping.
I think Candy's answer is mostly correct. There is one small part I think otherwise.
To map host:port/context/hello.jsp
No exact URL servlets installed, next.
Found wildcard paths servlets, return.
I believe that why "/*" does not match host:port/context/hello because it treats "/hello" as a path instead of a file (since it does not have an extension).
The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
I have two web applications.But only one among them includes Java servlet class.I want to access that servlet class from within the web.xml file of other application.Is it possible?.If yes,How will be it possible?.
You can't do that in the web.xml. You can however create a new servlet which in turn redirects/forwards the request to the servlet of the other webapplication. Redirecting is easy, just let the URL point to the particular servlet.
response.sendRedirect("/otherwebapp/theservlet");
Forwarding requires a bit more work. This is by default not possible due to security restrictions. First you need to configure the servletcontainer to enable cross context access between the webapplications in question. It's unclear which one you're using, so here's just a Tomcat targeted example so that you understand in what direction you should look for your own servletcontainer: for the both webapps, you need to set the crossContext attribute of the <Context> element to true:
<Context crossContext="true">
This way you can obtain the other context by ServletContext#getContext() inside a servlet:
ServletContext othercontext = getServletContext().getContext("/otherwebapp");
Finally you can forward the request through it as follows:
othercontext.getRequestDispatcher("/theservlet").forward(request, response);