2012-03-08 23 views
23

我使用AppFuse創建了一個基本的應用程序外殼程序,並遵循AppFuse tutorial以使用Jax-RS創建一個簡單的RESTful服務。這工作得很好。對http://localhost:8080/services/api/persons的調用返回Person對象的集合,作爲具有正確數據的Json格式的字符串。在Jax Rs/Appfuse應用程序中獲取HttpServletRequest?

我現在想訪問ServletRequestServletResponse對象從Appfuse公開的RESTful服務中(使用另一個需要這些對象的庫)。

I 認爲應該通過添加@Context註釋來實現,例如,在此之後StackOverflow post和這forum post

但是,如果我添加@Context標記(見下文),它編譯正常,但在服務器重新啓動時(附在底部)時拋出異常。

這裏的@WebService聲明:

@WebService 
@Path("/persons") 
public interface PersonManager extends GenericManager<Person, Long> { 
    @Path("/") 
    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
    List<Person> read(); 
    ... 
} 

而這裏的實現類,我想我會打電話@Context註釋:

@Service("personManager") 
public class PersonManagerImpl extends GenericManagerImpl<Person, Long> implements PersonManager { 
    PersonDao personDao; 
    @Context ServletRequest request; // Exception thrown on launch if this is present 
    @Context ServletContext context; // Exception thrown on launch of this is present 
    ... 
    } 

希望我失去了一些東西簡單,無論是什麼包括使其工作,或意識到獲得ServletRequest不應該是可能的,因爲......任何線索都會受到歡迎。

我在IntelliJ的Tomcat上運行這個。

===異常堆棧跟蹤(截斷)===

Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: 
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'serviceBeans' threw exception; nested exception is java.lang.RuntimeException: java.lang.NullPointerException 
     at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102) 
     at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58) 
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358) 
     ... 37 more 

回答

33

嘗試直接注射HttpServletRequestHttpServletContext

@Context private HttpServletRequest servletRequest; 
@Context private HttpServletContext servletContext; 
+1

非常感謝!儘管這並沒有完全按照書面的方式工作,但它給出了一個不同的異常,並且加上引用HttpServletRequest而不僅僅是ServletRequest的想法是弄清楚如何正確包含它的完美線索。是一個+1而不是檢查合適嗎? – prototype 2012-03-09 01:45:00

+0

嗯,這是奇怪的。我實際上是直接從一個正常運行的程序粘貼代碼。隨意發佈您的解決方案作爲答案,以便它可以使其他人受益。 – Perception 2012-03-09 02:42:19

+0

然後,我需要添加另一個項目,以添加到我的列表中,以瞭解如何使用安靜的服務。知道這也是有幫助的。再次感謝! – prototype 2012-03-09 17:46:23

23

它添加到方法簽名工作。我想這是因爲當類被實例化時請求和響應對象還不存在,但當被瀏覽器調用時,請求和響應對象不存在。

@Path("/") 
@GET 
@Produces(MediaType.APPLICATION_JSON) 
List<Person> read(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) { } 
+0

奇怪的是,即使沒有使用Spring或其他CDI框架,它也能工作。 – coladict 2017-07-18 14:59:42

相關問題