java web如何获取ServletContext

Filter

在javax.servlet.Filter中直接获取


ServletContext context = config.getServletContext();


HttpServlet

在HttpServlet中直接获取


this.getServletContext()


其他情况

在其他方法中,通过HttpRequest获得


request.getSession().getServletContext();


 


struts2

在struts2中还有常见的两种方法获得


获取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse对象

方法一,通过ServletActionContext.类直接获取:


HttpServletRequest request = ServletActionContext.getRequest();

request.getSession();

ServletContext servletContext = ServletActionContext.getServletContext();

HttpServletResponse response = ServletActionContext.getResponse();



方法二,实现指定接口,由struts框架运行时注入:

public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{

private HttpServletRequest request;

private ServletContext servletContext;

private HttpServletResponse response;

public void setServletRequest(HttpServletRequest req) {

this.request=req;

}

public void setServletResponse(HttpServletResponse res) {

this.response=res;

}

public void setServletContext(ServletContext ser) {

this.servletContext=ser;

}

}



参考

http://blog.sina.com.cn/s/blog_3fe961ae0100wjnf.html

你可能感兴趣的:(servlet&jsp)