我正在使用使用Servlet 2.5的Tomcat 6.ServletRequestAPI 中的Servlet 3.0中提供了一种方法,该方法为ServletContext与之关联的对象提供了句柄ServletRequest.有没有办法ServletContext从ServletRequest使用Servlet 2.5 API 获取对象?
Bal*_*usC 80
你可以通过HttpSession#getServletContext().
ServletContext context = request.getSession().getServletContext();
Run Code Online (Sandbox Code Playgroud)
然而,这可能在不期望时不必要地创建会话.
但是当你已经坐在HttpServlet类的实例中时,只需使用继承的GenericServlet#getServletContext()方法.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,当您已经坐在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();
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72058 次 |
| 最近记录: |