简体   繁体   English

从Servlet访问Tomcat上下文路径

[英]Accessing Tomcat Context Path from Servlet

In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying. 在我的Servlet中,我想访问上下文的根,以便我可以做一些JavaScript缩小。

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. 可以将minify作为安装过程的一部分进行,但我想在Servlet启动时执行此操作以降低实现成本。

Does anyone know of a method for getting the context directory so that I can load and write files to disk? 有谁知道获取上下文目录的方法,以便我可以加载和写入磁盘文件?

This should give you the real path that you can use to extract / edit files. 这应该为您提供可用于提取/编辑文件的真实路径。

Javadoc Link 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 在我的Servlet中,我想访问上下文的根,以便我可以做一些JavaScript缩小

You can also access the files in the WebContent by ServletContext#getResource() . 您还可以通过ServletContext#getResource()访问WebContent中的文件。 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: 因此,如果您的JS文件位于WebContent/js/file.js那么您可以在Servlet使用以下内容来获取它的File句柄:

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

or to get an InputStream : 或者获取InputStream

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

That said, how often do you need to minify JS files? 那就是说,你需要多久缩小一次JS文件? 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. 如果是这样,那么使用Servlet是一个坏主意。 Better use ServletContextListener and do your thing on contextInitialized() . 更好地使用ServletContextListener并在contextInitialized()上执行您的操作。

I was googling the result and getting no where. 我在谷歌搜索结果,没有在哪里。 In JSP pages that need to use Java Script to access the current contextPath it is actually quite easy. 在需要使用Java Script访问当前contextPath的 JSP页面中,它实际上非常简单。

Just put the following lines into your html head inside a script block. 只需将以下行放入script块中的html头部即可

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

Do you mean: 你的意思是:

public class MyServlet extends HttpServlet {

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

    ...
}

Or something more complex? 还是更复杂的东西?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM