Reputation: 143
I'm currently trying to set a context path for a config file in my webapp, but it seems no matter what solution I try, none of them give the right path. The config file is found in WEB-INF/Config.
I've tried using ServletContextAware
in order to grab the context path, but it seems to give me the wrong path.
C:\Documents and Settings\Person\My Documents\geronimo-tomcat6-javaee5-2.2-bin\geronimo-tomcat6-javaee5-2.2\bin\org.apache.catalina.core.ApplicationContextFacade@5d869c\WEB-INF\config\config.xml
private ServletContext context;
public void setServletContext(ServletContext context) {
this.context = context;
}
AdminFile = builder.parse(context + "/WEB-INF/config/config.xml");
I've also tried creating a context path through org.apache.struts2.ServletActionContext, by calling ServletActionContext.getServletContext, but that gives me a similar error.
C:\Documents and Settings\Person\My Documents\geronimo-tomcat6-javaee5-2.2-bin\geronimo-tomcat6-javaee5-2.2\bin\org.apache.catalina.core.ApplicationContextFacade@156592a\WEB-INF\config\config.xml
ServletContext context = ServletActionContext.getServletContext();
AdminFile = builder.parse(context + "/WEB-INF/config/config.xml");
I finally tried using ServletRequestAware, and it gave me better results, but still not the full context path I need. I would also like to avoid coupling my action class to the servlet api.
\JSPPrototype\WEB-INF\config\config.xml
public HttpServletRequest request;
public void setServletRequest(HttpServletRequest request)
{
this.request = request;
}
String context = request.getContextPath();
AdminFile = builder.parse(context + "/WEB-INF/config/config.xml");
What exactly am I doing wrong, and how should I build a ContextPath that works?
Upvotes: 0
Views: 2831
Reputation: 13821
The ServletContext
is not the same as the context path of your application. The ServletContext
is an object that your web application can use to interface with the servlet container. Hence, what you're doing with your approach is to concatenate that object with a String
, which invokes it's toString()
method, which just prints the implementing class name and it's hashcode. Which obviously does not match your path.
What you instead need to do is to use the ServletContext
to get a URL
to your file. And to do that, you actually use the ServletContext
. You can get the URL
of a file in your web application with the getResource
method of the ServletContext
. Something like this:
builder.parse(context.getResource('/WEB-INF/config/config.xml'));
This requires your parse
method to accept a URL
object. You can also use getResourceAsStream()
, if your builder accepts a parameter of type InputStream
instead.
Upvotes: 3