随笔-9  评论-168  文章-266  trackbacks-0
在spring的bean中获取ServletContext 和 servletConfig
  常规方式下获取servletContext需要继承HttpServlet类,然后获取servletConfig,通过这个获取servletContext(servletConfig.getServletContext())。
  但是spring的bean都是pojo,和我们常规的操作有些不同。
spring给我们提供了两个接口:org.springframework.web.context.ServletContextAware和org.springframework.web.context.ServletConfigAware。我们可以让我们的bean实现上边的任何一个接口就能获取到servletContext了 .
代码如下:
public class DicBean implements ServletContextAware{
    
private ServletContext servletContext;

public void setServletContext(ServletContext sc) {
    
this.servletContext=sc;
    System.out.println(
"项目应用的绝对路径为:"+servletContext.getRealPath("/"));
}
}
posted on 2011-06-18 09:44 紫蝶∏飛揚↗ 阅读(2781) 评论(0)  编辑  收藏 所属分类: Spring重点JSP

只有注册用户登录后才能发表评论。


网站导航: