将HttpServlet请求注入rest服务



我想通过@Context注释将HttpServlet请求注入到我的服务中。这是我的例子:

@Path("/")
public class MyService {
    @Context
    private HttpServletRequest request;
}

我使用ApacheCXF实现,下面是pom.xml中的依赖项:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.1.7</version>
</dependency>
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0</version>
</dependency>

此外,我使用ApacheKaraf OSGI容器进行部署,这就是为什么我的应用程序是捆绑包封装类型的原因。有这样的配置:

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <version>3.5.0</version>
    <configuration>
        <instructions>
            <Import-Package>
                !*,
                javax.ws.rs,
                javax.ws.rs.core,
                javax.ws.rs.ext,
                org.apache.cxf.jaxrs.impl.tl,
            </Import-Package>
            <Embed-Transitive>true</Embed-Transitive>
        </instructions>
    </configuration>
</plugin>

在导入包部分没有javax.ws.rs.extorg.apache.cxf.jaxrs.impl.tl,我得到了其中一个例外:

Caused by: java.lang.IllegalArgumentException: interface javax.ws.rs.ext.Providers is not visible from class loader 
Caused by: java.lang.IllegalArgumentException: interface org.apache.cxf.jaxrs.impl.tl.ThreadLocalProxy is not visible from class loader 

所以现在我在尝试部署我的应用程序时出现了以下异常:

Caused by: java.lang.IllegalArgumentException: Can not set javax.servlet.http.HttpServletRequest field MyService.request to org.apache.cxf.jaxrs.impl.tl.ThreadLocalHttpServletRequest

我花了很多时间来弄清楚问题出在哪里。。但我注意到一件事:

如果我使用ThreadLocalHttpServletRequest request如果不是HttpServletRequest request,那么它毫无例外地工作,但是当我尝试从任何方法使用它时,request字段都是null

我应该怎么做才能使它与HttpServletReqest正常工作?

尝试使用org.apache.cxf.jaxrs.ext.MessageContext

import javax.ws.rs.core.Context;
import org.apache.cxf.jaxrs.ext.MessageContext;

// your code goes like this
@Context 
private MessageContext context;

// try to get the request/response/session etc in your methods
HttpServletRequest req = context.getHttpServletRequest();
HttpServletResponse res = context.getHttpServletResponse()

最新更新