29

我使用 AppFuse 创建了一个基本的应用程序外壳,并按照AppFuse 教程使用 Jax-RS 创建了一个简单的 RESTful 服务。这工作得很好。调用http://localhost:8080/services/api/persons将 Person 对象集合作为具有正确数据的 Json 格式字符串返回。

我现在想从 Appfuse 公开的 RESTful 服务 中访问ServletRequest和对象(以使用需要这些对象的另一个库)。ServletResponse

认为这应该可以通过添加一个@Context 注释来实现,例如在这个StackOverflow 帖子和这个论坛帖子之后

但是,如果我添加 @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 
4

2 回答 2

44

尝试直接注入HttpServletRequestand HttpServletContext

@Context private HttpServletRequest servletRequest;
@Context private HttpServletContext servletContext;
于 2012-03-08T04:03:45.730 回答
30

将其添加到方法签名中有效。我想这是因为在实例化类时请求和响应对象还不存在,但在浏览器调用时存在。

@Path("/")
@GET
@Produces(MediaType.APPLICATION_JSON)
List<Person> read( @Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) { }
于 2012-03-09T01:38:24.297 回答