2016-07-23 31 views
0

我的高級目標是使用由NetBeans生成的JPA代碼,通過使用在我的servlet中創建「來自數據庫的REST風格的Web服務」嚮導。如何將無狀態會話bean注入到servlet中?

更確切地說,我想直接從servlet訪問Facade,以避免在客戶端使用JavaScript加載一些數據。

我的門面的相關部分看起來是這樣的:

@Stateless 
@Path("wgm.rest.balanceview") 
public class BalanceViewFacadeREST extends AbstractFacade<BalanceView> { 

    @PersistenceContext(unitName = "WGManagerPU") 
    private EntityManager em; 

    @GET 
    @Override 
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 
    public List<BalanceView> findAll() { 
    return super.findAll(); 
    } 

} 

現在我試過如下:

@WebServlet(name = "BalanceServlet", urlPatterns = "/balance/*") 
public class BalanceServlet extends HttpServlet { 

    @Inject 
    private BalanceViewFacadeREST balanceFacade; 


    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
    ServletException, IOException { 
    List<BalanceView> balances = balanceFacade.findAll(); 
    // ... 
    } 
} 

但是,在部署到GlassFish時,我得到以下異常:

java.lang.RuntimeException: Unable to load the EJB module. DeploymentContext does not contain any EJB. Check the archive to ensure correct packaging for /home/severin/Projects/WGManager/build/web. 
If you use EJB component annotations to define the EJB, and an ejb or web deployment descriptor is also used, please make sure that the deployment descriptor references a Java EE 5 or higher version schema, and that the metadata-complete attribute is not set to true, so the component annotations can be processed as expected 

這聽起來像是我注射器無法找到BalanceViewFacadeREST。我錯過了什麼?

回答

2

我認爲你的Servlet和你的EJB是彼此本地的。我的推定是基於你的EJB沒有遠程接口。

如果Servlet和EJB駐留在同一個容器中,則只需在容器中注入上下文和依賴注入,就可以使用@EJB或@Inject進行偏移。

由於您既不呈現REMOTE也不呈現LOCAL接口,因此您的EJB是無接口類型的。這意味着你應該註釋EJB與@LocalBean

@Stateless 
@LocalBean 
@Path("wgm.rest.balanceview") 
public class BalanceViewFacadeREST 



//@Inject 
    OR 
// @EJB 
    private BalanceViewFacadeREST balanceFacade; 
+0

謝謝!不幸的是,我對EJB真的很陌生,所以我不知道爲什麼我們需要@LocalBean,但我想我將不得不深入探討這個主題。 無論如何,這解決了上述問題,但現在我得到一個嚴重的日誌消息: 「Severe:Class [Lwgm/rest/service/BalanceViewFacadeREST;] not found。Error loading while [class wgm.servlets.BalanceServlet]」and I爲我的所有路徑獲取404(也是與/無關的路徑)。這可能是相關的還是這是另一個問題?順便說一句,即時通訊使用Glassfish版本4.1.1。 – Severin

+0

因爲我完全清理並重建了應用程序並刪除了Glassfish中的'generated'和'osgi-chache'目錄(只是可以肯定),所以我不再收到嚴重的日誌消息。 NetBeans部署到Glassfish似乎是一個問題。當我手動將War-archive複製到Glassfish autodeploy文件夾時,它工作正常。但我想我會爲這個問題提出一個新的問題。 – Severin

相關問題