您可以通过HttpSession#getServletContext()
得到它。
ServletContext context = request.getSession().getServletContext();
然而,这可能会在不需要时创建会话。
但是,当您已经坐在HttpServlet
类的实例中时,只需使用继承的GenericServlet#getServletContext()
方法即可。
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
// ...
}
或者当你已经坐在Filter
接口的实例,只要使用FilterConfig#getServletContext()
。
private FilterConfig config;
@Override
public void init(FilterConfig config) {
this.config = config;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
ServletContext context = config.getServletContext();
// ...
}
并在JSP http://stackoverflow.com/questions/2898390/java-jsp-servlet-equivalent-of-getservletcontext-from-inside-a-jsp – tgkprog
@tgkprog:神圣的,请不! – BalusC
只是为了测试,然后放入一个过滤器 – tgkprog