How to get the contextPath in a servlet's init-method?

S

Stephan Koser

Hi,

is there a way to get the context path inside the servlet's init-method?
In an URL like http://localhost/myApp/... i want to get the Attribute
/myApp.

I know, I can get ist with HttpServletRequest#getContextPath(), but in the
init method I don't have a servletRequest.
Is there another way to get it that also works with different Java
Containers?

...
bye Stephan...
 
A

au714

Stephan said:
Hi,

is there a way to get the context path inside the servlet's init-method?
In an URL like http://localhost/myApp/... i want to get the Attribute
/myApp.

public void init() throws ServletException {
ServletContext context = getServletContext();
System.out.println("Real Path = " + context.getRealPath("/"));
}
 
J

John C. Bollinger

public void init() throws ServletException {
ServletContext context = getServletContext();
System.out.println("Real Path = " + context.getRealPath("/"));
}

That doesn't answer the question posed. The real path to the context
root does not necessarily have anything at all to do with the context
path relative to the server root.

In answer to the OP's question, it is not possible to do what you want
in general, because the same servlet may be accessible via more than one
path. The context path is partly a function of the request, which is
why it is only available from the request object. If you _really_ need
this information at init time (and you probably don't), then you can
fudge by putting it in one of the servlet's init parameters. This
probably will introduce a dependency between the webapp's deployment
descriptor and the servlet container's configuration, so do not
undertake it lightly.


John Bollinger
(e-mail address removed)
 
G

gimme_this_gimme_that

Would setting a parameter/value pair to the startup servlet in the
web.xml file and then using
that be a satisfactory solution?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top