Access Tomcat context path from servlet

In my servlet, I would like to access the context root so that I can execute some JavaScript shortcuts.

It would be possible to perform minify as part of the installation process, but I would like to do this when starting Servlet in order to reduce the implementation cost.

Does anyone know a method to get the context directory so that I can upload and write files to disk?

+6
java tomcat servlets
source share
4 answers

This should give you a real path that you can use to extract / edit files.

Javadoc link

We do something like this in a context listener.

public class MyServlet extends HttpServlet { public void init(final ServletConfig config) { final String context = config.getServletContext().getRealPath("/"); ... } ... } 
+13
source share

In my servlet, I would like to access the context root so that I can execute some kind of JavaScript shortening

You can also access files in WebContent using ServletContext#getResource() . Therefore, if your JS file, for example, is located in WebContent/js/file.js , you can use the following in Servlet to get the File descriptor:

 File file = new File(getServletContext().getResource("/js/file.js").getFile()); 

or get an InputStream :

 InputStream input = getServletContext().getResourceAsStream("/js/file.js"); 

However, how often do you need to minimize JS files? I have never seen the need to minimize queries, this would only unnecessarily increase the overhead. You will probably want to do this only once during the launch of the application. If so, using Servlet for this is a bad idea. Better use ServletContextListener and do your thing on contextInitialized() .

+2
source share

I searched for the result and got nothing. On JSP pages that must use Java Script to access the current contextPath, this is actually quite simple.

Just insert the following lines into the html line in the script block.

 // set up a global java script variable to access the context path var contextPath = "${request.contextPath}" 
0
source share

Do you mean:

 public class MyServlet extends HttpServlet { public void init(final ServletConfig config) { final String context = config.getServletContext(); ... } ... } 

Or something more complicated?

-one
source share

All Articles