In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.
It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.
Does anyone know of a method for getting the context directory so that I can load and write files to disk?
The context path refers to the location relative to the server's address which represents the name of the web application. By default, Tomcat derives it from the name of the deployed war-file. So if we deploy a file ExampleApp. war, it will be available at http://localhost:8080/ExampleApp.
context. xml file is the application deployment descriptor for the Apache Tomcat server. In a deployed application, this file is located in the META-INF folder of the web application directory or the WAR file, for example, tomcat/webapps/app-core/META-INF/context. xml .
The typical way of getting the context path is through the HttpServletRequest class. Simply you can add a HttpServletRequest parameter to your controller method and then get the context path using getContextPath() method.
The context path is the portion of the request URI that is used to select the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "".
This should give you the real path that you can use to extract / edit files.
Javadoc Link
We're doing something similar in a context listener.
public class MyServlet extends HttpServlet {
public void init(final ServletConfig config) {
final String context = config.getServletContext().getRealPath("/");
...
}
...
}
In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying
You can also access the files in the WebContent by ServletContext#getResource()
. So if your JS file is for example located at WebContent/js/file.js
then you can use the following in your Servlet
to get a File
handle of it:
File file = new File(getServletContext().getResource("/js/file.js").getFile());
or to get an InputStream
:
InputStream input = getServletContext().getResourceAsStream("/js/file.js");
That said, how often do you need to minify JS files? I have never seen the need for request-based minifying, it would only unnecessarily add much overhead. You probably want to do it only once during application's startup. If so, then using a Servlet
for this is a bad idea. Better use ServletContextListener
and do your thing on contextInitialized()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With