Java – How to get web application path outside of a JSP page

javajsp

I am new to JSP and Java EE. So maybe there is something very obvious that I missed.

I have a web filter class that needs to redirect the web request back to the root of the current web application. But since our application is not deployed in the root, I need to know the path the the current web application.

e.g. http://www.mydomain.com/myapplication/index.htm

I need to get the "myapplicaiton" part.

I have tried ServletContext, ApplicationContext with no success. I realized I can get it from HttpServletRequest but I don't have access to it in my filter class.

Please help. I am stuck. I am from the .NET world. And this is so easy there.

Best Solution

Depending on your Servlet version, you might not be able to get it without a request. Before Servlet 2.5, it makes assumption that a servlet may have multiple context paths so you can only get it from a request. This is changed in 2.5 and ServletContext.getContexPath() is added.

If you need this in doFilter(), you have access to the request. If you really want do this in init() on Tomcat 5.5 or earlier version, you can do a hack,

String contextPath = ((org.apache.catalina.core.ApplicationContext)filterConfig.getSevletContext()).getContextPath();

Of course, this wouldn't be portable.

Related Question