.如何在quartz裏使用request獲取指定的文件路徑
a.使用servlet監聽器,在容器啓動的時候,獲取ServletContext並將其放到SchedulerContext裏,代碼如下:
public class QuartzListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0)
{
//TODO
}
public void contextInitialized(ServletContextEvent servletContextEvent)
{
Scheduler sched = new StdSchedulerFactory().getScheduler();
sched.getContext().put("servletContext", servletContextEvent.getServletContext());
.......
}
}
b.在job裏獲取ServletContext,然後通過ServletContext的API獲取想要的值,以獲取web目錄的絕對路徑爲例:
public class FileDownload extends StatefulMethodInvokingJob
{
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException
{
try
{
//從SchedulerContext獲取此前監聽器放入的ServletContext
ServletContext servletContext =(ServletContext)context.getScheduler().getContext().get("servletContext");
String dir=servletContext.getRealPath("static/downloadfiles");
......
} catch (Exception e)
{
e.printStackTrace();
}
}
}
別忘了配置監聽,這個是基礎就不再贅述了。