How do I install a servlet in a tomcat container and have it loaded into each web app's context?

132 views Asked by At

I'm currently using Tomcat 7. I want to deploy/install a servlet that will be loaded in each webapp in their context. I am looking for a solution that doesn't involve me adding the servlet to each webapp's war. Is this possible?

Ultimately, I want it to service requests on a common subpath of each webapp's context root.

I was thinking maybe I could load an annotated servlet from the tomcat common classloader, but I couldn't get that to work. For example, same annotated servlet worked in the war, but not in the common classloader.

@WebServlet(
    description = "Says Hello", 
    urlPatterns = { "/HelloServlet" })
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // log hello
    }
}

Thanks for you help.

2

There are 2 answers

2
Dimos On

The thing you describe is not exactly compatible with the logic of Servlets.

If you want to use a service/library from 2 different applications in Tomcat, then you can add a library as shared library in Tomcat. Then, you will be able to use this library from your application servlets. If you want to achieve this, you will have to add the jar in $CATALINA_HOME/shared/lib and then edit $CATALINA_HOME/conf/catalina.properties to add {catalina.home}/mylibs/*.jar in common.loader property. Then, you will be able to use your library in the various servlets of your applications.

However, this is different to what you describe. In fact, what you describe is infeasible in Tomcat, since each web application has its own ApplicationContext. Thus, webappA's Application context will be http://host/webappA and webappB's application context will be http://host/webappB. So, if you want to have a servlet outside those 2 applications, then this servlet will belong to a different ApplicationContext. So, it won't be possible to access this servlet through either of paths http://host/webappA/common, http://host/webappB/common, that belong to the previous ApplicationContexts.

0
cosbor11 On

You can do this using a war overlay.