Recipe 3.5 Invoking a Servlet Without a web.xml MappingProblemYou want to request a servlet that does not have a servlet-mapping element in the web.xml deployment descriptor. SolutionUse an invoker-style URL of the form http://www.mysite.org/mywebapp/servlet/com.jspservletcookbook.MyServlet . Discussion
Some servlets may not have a
Tomcat and other servlet containers provide a method for invoking servlets that are not mapped in web.xml . You can use a URL of the following form: http://www.mysite.org/mywebapp/servlet/<fully qualified class name of servlet>
A servlet with the class and package name of
jspservletcookbook.MyServlet
is invoked as
http://www.mysite.org/mywebapp/servlet/jspservletcookbook.MyServlet
. Ensure that the path segment following the name of your web application is
/servlet/
and not
/servlets/
. If the servlet is stored in the default web application (
The web.xml file located in <Tomcat_install_directory>/conf includes this definition and mapping for the invoker servlet:
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>org.apache.catalina.servlets.InvokerServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
The invoker servlet can also be used to invoke the servlets that are registered in web.xml . These URLs look like http://www.mysite.org/cookbook/servlet/<RegisteredServletName> . For instance, imagine you have a servlet element like this: <servlet> <servlet-name>myservlet</servlet-name> <servlet-class>jspservletcookbook.MyServlet</servlet-class> </servlet> Consider that the web application context path is /cookbook . If the Tomcat invoker servlet is enabled in this application, then this servlet can be invoked with its registered name at http://www.mysite.org/cookbook/servlet/myservlet .
If a servlet is
Example 3-7. A registered servlet with init parameters
<servlet>
<servlet-name>Weather</servlet-name>
<servlet-class>home.Weather</servlet-class>
<init-param>
<param-name>region</param-name>
<param-value>New England</param-value>
</init-param>
</servlet>
Because it is the registered name of the servlet that has the region parameter assigned to it, only a request for that registered name (or a servlet path mapped to that name) triggers the region parameters. Accessing the servlet through its fully qualified name will not result in the region parameter being passed to the Weather servlet. See Also
Chapter 1 on
web.xml
; Recipe 3.1-Recipe 3.4; Recipe 3.6-Recipe 3.8; Chapter 11 of the Servlet v2.3 and 2.4 specifications on mapping
|