This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have the following problem : i wrote a webapp which is deployed under Tomcat , this webapp is for several clients with a custom name for each of them.
I need to get the name of the webapp that is configured in the Tomcat server.xml (not in the web.xml) because this name change for differents clients and i need it for my business operations. I want to read the name at the startup of the Tomcat. So i try to write a custome Listner but i only access to the ServletContext and i can't find the way to get the name !
I don't want specially write a listner so if you have another solution to solve my problem i am ok !
Would it be possible to just set the webapp name in the web.xml as context-param entry, instead of reading from server.xml? Then, you would just need to invoke ServletContext.getInitParameter to get the name. I know this sounds deviate from your requirement, but this ensure better portability when your application migrate to other platform. You might also want to try to explore the tomcat context, using javax.naming.Context.
SCJP, SCWCD, SCJWS, IBM 700,IBM 701, IBM 704, IBM 705, CA Clarity Technical<br /> <br /><a href="http://eddyleesinti.blogspot.com" target="_blank" rel="nofollow">http://eddyleesinti.blogspot.com</a>
I had this same question a few months ago and was unable to find a satisfactory answer. <opinion> With the contextListener, they (the Servlet Spec) should have added a method to get the contextPath from the ServletContext object. </opinion>
I got this ugly hack to work but I didn't feel comfortable putting it into production myself so.. buyer beware:
Ben : I agree with you for the specs .... your code seems to work perfectly why are you saying : I didn't feel comfortable putting it into production myself so..buyer beware: ? Stef
I just don't feel comfortable parsing the results of that call to find the contextPath.
If you're going to use that, I would recommend putting some checks to make sure that you get back a string that can be parsed that way. Also, I'm not sure what comes back if the app is deployed from an un-exploded war file.
I just tried putting that in a jsp scriptlet and ran it from the default application (ROOT) and it returned: "localhost". Probably not what you would have expected.
My point was that getResource is meant to return a URL to a resorce within the webapp. It was not intended that developers would parse a string representation of the URL to pluck the contextPath from it. Any time you rely on an uninteneded side effect of a method, you risk having it come back to bite you.
If you're relying on the value for something important, make sure you do a lot of testing, in any container that you intend to support.