参考文章:
http://www.oschina.net/code/snippet_1579_2199
众所周知在控制器,获取web根目录只要调用以下这行代码就可以了:
servletContext.getRealPath("/")
然而在服务类中没有servletContext,这下麻烦大了,
如何得到servletContext呢?困扰了我好久。。。
解法方法:
1、在服务类中声明grailsApplication,然后就可以使用其中的方法获取servletContext了
众所周知在控制器,获取web根目录只要调用以下这行代码就可以了:
servletContext.getRealPath("/")
然而在服务类中没有servletContext,这下麻烦大了,
如何得到servletContext呢?困扰了我好久。。。
解法方法:
1、在服务类中声明grailsApplication,然后就可以使用其中的方法获取servletContext了
如:
class TestService{
def grailsApplication
def getSaveDir(){
String dir = grailsApplication.getMainContext().servletContext.getRealPath("/") + "images"
return dir
}
}
-------------------------------------------------------------------------------------------------