2012-05-22 53 views
3

在我的webapp中,我使用Quartz以某個間隔調用某個類中定義的方法,該方法作爲其中一個參數需要一個指向我的WebContent目錄中的css文件的路徑。我的問題是如何從非servlet類獲取該css文件的路徑。我也嘗試在非servlet類中獲取上下文路徑

的一件事是我做的,調用該方法延長HttpServlet,這樣我可以打個電話給

String contextPath = getServletContext().getRealPath(""); 

,但沒有工作,我的應用程序只是掛在該行的類。 我不想硬編碼路徑,因爲這看起來不專業:)

回答

3

您不能從Quartz作業訪問servlet上下文,因爲作業不作爲請求處理管道的一部分調用。

爲什麼不讓CSS文件路徑成爲作業的參數,以便它可以通過調用/調用Quartz作業的servlet/web-code傳遞?一個例子見the Quartz documentation

+0

石英計劃的工作是一種方法,它採用參數文件路徑之一。 – SneakyMummin

+0

當您的代碼安排作業時,是否將參數值傳遞給Quartz,在JobDetail.setJobDataMap()中? –

+0

這樣做。謝謝 – SneakyMummin

1

如果您將文件放入Web應用程序的WEB-INF/classes目錄中,則可以使用getResourceAsStream()來訪問它。這將與WAR文件一起工作; getRealPath()不會。

爲什麼Quartz需要知道.css文件?這應該是純粹的看法。

+0

Quartz不關心.css文件。它的石英調用方法需要css路徑 – SneakyMummin

+0

無法想象爲什麼。 Quartz在服務器端安排一項任務; .css應該是關於查看。仍然不明白,但我不必這樣做。祝你好運。 – duffymo

0

不,我們可以從Quartz作業訪問servlet上下文。

@Override 
public void contextInitialized(ServletContextEvent sce) { 
    try { 
     //Create & start the scheduler. 
     StdSchedulerFactory factory = new StdSchedulerFactory(); 
     factory.initialize(sce.getServletContext().getResourceAsStream("/WEB-INF/my_quartz.properties")); 
     scheduler = factory.getScheduler(); 
     //pass the servlet context to the job 
     JobDataMap jobDataMap = new JobDataMap(); 
     jobDataMap.put("servletContext", sce.getServletContext()); 
     // define the job and tie it to our job's class 
     JobDetail job = newJob(ImageCheckJob.class).withIdentity("job1", "group1").usingJobData(jobDataMap).build(); 
     // Trigger the job to run now, and then repeat every 3 seconds 
     Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow() 
       .withSchedule(simpleSchedule().withIntervalInMilliseconds(3000L).repeatForever()).build(); 
     // Tell quartz to schedule the job using our trigger 
     scheduler.scheduleJob(job, trigger); 
     // and start it off 
     scheduler.start(); 
    } catch (SchedulerException ex) { 
     log.error(null, ex); 
    } 
} 

石英工作,我們得到CA servlet上下文如下。

@Override 
public void execute(JobExecutionContext context) throws JobExecutionException { 
    ServletContext servletContext = (ServletContext) context.getMergedJobDataMap().get("servletContext"); 
    //... 
}