【问题标题】:Get HttpServletRequest in Jax Rs / Appfuse application?在 Jax Rs / Appfuse 应用程序中获取 HttpServletRequest?
【发布时间】:2012-03-25 14:43:17
【问题描述】:

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

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

认为 这应该可以通过添加 @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 

【问题讨论】:

    标签: java rest servlets jax-rs appfuse


    【解决方案1】:

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

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

    【讨论】:

    • 令人惊讶的是,即使没有使用 Spring 或其他 CDI 框架,它也能正常工作。
    【解决方案2】:

    尝试直接注入HttpServletRequestHttpServletContext

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

    【讨论】:

    • 非常感谢!尽管这与写的不完全一样,但它给出了一个不同的异常,加上引用 HttpServletRequest 而不仅仅是 ServletRequest 的想法是弄清楚如何正确包含它的完美线索。 +1 而不是检查是否合适?
    • 嗯,这很奇怪。我实际上是直接从一个正常运行的程序中粘贴了代码。随时发布您的解决方案作为答案,以便其他人受益。
    • 那么我必须将另一个项目添加到我的清单中,以了解 restful 服务的工作原理。知道这一点也很有帮助。再次感谢!
    • 此选项强制您使用实例变量,您可能希望将其用作方法参数来注入请求、响应变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 2013-07-26
    • 2015-06-13
    • 1970-01-01
    • 2016-08-17
    相关资源
    最近更新 更多