Reputation: 81
I have an entry servlet (called DispatcherServlet) which redirects all incoming GET and POST requests at /* to other servlets depending on a configuration parameter. In order to dispatch the request to other servlets, I use their name instead of a path, because my DispatcherServlet would end up in an endless loop while listening to /*.
The "old" way was to give servlets a name in the web.xml descriptor:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>mypackage.MyServlet</servlet-class>
</servlet>
Afterwards, one is able to address the servlet by its name, for example, when using a RequestDispatcher
. The code in my DispatcherServlet looks like this:
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("MyServlet"); dispatcher.forward(request, response);
This works perfectly. But, I would like to use the "new" Servlet 3 annotations without the web.xml, hence I do this:
@WebServlet(name="MyServlet")
public class MyServlet extends HttpServlet {
...
But now, getServletContext().getNamedDispatcher("MyServlet")
within my DispatcherServlet returns null instead of the appropriate dispatcher for MyServlet
, although I expect that @WebServlet(name="MyServlet")
behaves the same like <servlet-name>MyServlet</servlet-name>
I have tested this on Tomcat 7.
Is this because MyServlet has not been loaded yet by the time when DispatcherServlet is called and hence the name of MyServlet is not known? If so, what sense does the @WebServlet(name="...")
annotation make ;)
Please don't answer with something like "why don't you use filters?" etc. This is more about the background of annotations vs. web.xml
Thanks in advance!
(ps. please change the title if you find a more suitable one ;))
Upvotes: 2
Views: 913
Reputation: 13639
By just comment with @WebServlet
is not enough to load a Servlet into the Web container; you must include at least one URL pattern, and if you don't want to expose the Servlet to keep it for internal forward only, set the URL to start with '/WEB-INF/'.
And keep in mind that the 'name' property is buggy, so not use it.
@WebServlet(urlPatterns = "/WEB-INF/thisServlet")
public class FooServlet extends HttpServlet {
...
}
and to forward the request, call something like this:
servletContext.getNamedDispatcher(FooServlet.class.getName()).forward(request, response);
Upvotes: 0
Reputation: 1675
If you do not specify the urlMapping with the name, you will need do add the full class name. Like
RequestDispatcher dispatcher = getServletContext().
getNamedDispatcher("mypackage.MyServlet");
It works for me if the servlet is annotated as:
@WebServlet(urlPatterns="/Servlet", name="Servlet")
or better:
@WebServlet(urlPatterns="/Servlet", displayName="Servlet", name="Servlet")
Also, you can try to get your servlet name with:
getServletName()
Upvotes: 0