You can get it by the HttpSession#getServletContext()
.
ServletContext context = request.getSession().getServletContext();
This may however unnecessarily create the session when not desired.
But when you’re already sitting in an instance of the HttpServlet
class, just use the inherited GenericServlet#getServletContext()
method.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
// ...
}
Or when you’re already sitting in an instance of the Filter
interface, just use 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();
// ...
}