在spring的bean中获取ServletContext

[b] 我的需求是获取 ServletContext ,以获取Attribute中的变量,在页面application也可以获取[/b]

参考一下的文章
进而引申到我需要知道servletContext,因为servletContext有一个servletContext.getRealPath("/");方法,这个方法就能获取项目的绝对路径。
常规方式下我们如何获取servletContext呢?我们需要让我们的类继承HttpServlet类,然后获取servletConfig,通过这个获取servletContext(servletConfig.getServletContext())。(至于如何获取servletconfig对象,大家去google,百度找找吧)
但是我需要在spring的bean中直接获取,这下可和我们常规的操作有些不同,因为spring的bean都是pojo的。根本见不着servletconfig和servletcontext的影子。
这里我需要指出spring给我们提供了两个接口:org.springframework.web.context.ServletContextAware和
org.springframework.web.context.ServletConfigAware。我们可以让我们的bean实现上边的任何一个接口就能获取到servletContext了 .
代码如下:


view plaincopy to clipboardprint?


public class DicBean implements ServletContextAware{

private ServletContext servletContext;

public void setServletContext(ServletContext sc) {
this.servletContext=sc;
System.out.println("项目的绝对路径为:"+servletContext.getRealPath("/"));
}
}


public class DicBean implements ServletContextAware{
private ServletContext servletContext;
public void setServletContext(ServletContext sc) {
this.servletContext=sc;
System.out.println("项目的绝对路径为:"+servletContext.getRealPath("/"));
}
}

这样,我们的bean就能够直接获取到servletContext了
如果你想要servletConfig,那方法一样,只是实现的接口不同了。
原理推想:应该是在创建spring的sessionFactory的时候,将应用服务器的相关属性一并加载[url],查看创建的bean是否实现相关接口,如果实现了,就将相关值赋予bean。

来自:[url]http://www.zoomhoo.com/viewthread.jsp?tid=121[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值