2016-12-01 33 views
1

我有一個功能,看起來像這樣:Java是否可以發送一個httpServletRequest到一個函數?

@GET 
@Path("/execute/{scriptId}") 
public String execute(@Context HttpServletRequest req, @PathParam("scriptId") Long scriptId) { 

/* ... */ 
     engine.eval(getSrc(req.getServletContext().getRealPath("js/boot.js"))); 

     if (scriptId == 1L) 
       engine.eval(getSrc(req.getServletContext().getRealPath("js/test.js"))); 
     else 
       engine.eval(getSrc(req.getServletContext().getRealPath("js/test2.js"))); 

/* that above, its the only place i need the req */ 

} 

我把它從一個html頁面...

<a href="rest/dss/execute/1">execute 1</a> 

,它工作正常...

現在...我做了一個計時器....並在計時器中我需要調用該函數,但我不知道如何獲得該函數的httpservletrequest參數...

這裏是代碼:

@Timeout 
public void execute(Timer timer) { 
    Long scriptId = Long.parseLong(timer.getInfo().toString()); 
    execute(/*here i need something*/, scriptId); 

    System.out.println("Timer Service : " + scriptId); 
    System.out.println("Current Time : " + new Date()); 
    System.out.println("Next Timeout : " + timer.getNextTimeout()); 
    System.out.println("Time Remaining : " + timer.getTimeRemaining()); 
    System.out.println("____________________________________________"); 

} 

所以,基本上,我需要調用該函數與計時器...

什麼想法?

回答

0

當然,它只是一個你可以實現的接口。

當然,實現它來做一些有用的事情可能不是微不足道的,這取決於你在用另一種方法中的請求做什麼。

從某個實現JEE標準的第三方庫獲取HttpServletRequest的準備實現可能會有所幫助,但這可能會有所幫助。

+0

怎麼辦呢?只需下載庫和實現?然後呢?我仍然不知道如何調用函數 – begi

+0

所以最後,即使我實現了一些其他接口,我仍然不知道如何去做 – begi

+0

對於像這樣簡單的事情實現'HttpServletRequest'並不是一個好主意。我更喜歡@托馬斯的建議。 –

1

如果你的函數不需要HttpServletRequest(即它並不需要呼籲HttpServletRequest方法),那麼你可以提取現有的代碼到不依賴於一個HttpServletRequest並在execute方法的實現方法調用執行:

@GET 
@Path("/execute/{scriptId}") 
public String execute(@Context HttpServletRequest req, @PathParam("scriptId") Long scriptId) { 
    return executeImpl(scriptId); 
} 

public String executeImpl(Long scriptId) { 
    ...// your current implementation 
} 

然後你的計時器也可以調用這個方法:

@Timeout 
public void execute(Timer timer) { 
    Long scriptId = Long.parseLong(timer.getInfo().toString()); 
    executeImpl(scriptId); 

    System.out.println("Timer Service : " + scriptId); 
    System.out.println("Current Time : " + new Date()); 
    System.out.println("Next Timeout : " + timer.getNextTimeout()); 
    System.out.println("Time Remaining : " + timer.getTimeRemaining()); 
    System.out.println("____________________________________________"); 

} 
+0

但只在3行.... – begi

相關問題