将HttpServletRequest注入rest服务

时间:2018-11-14 19:45:07

标签: java rest servlets cxf

我想通过@Context注释将HttpServletRequest注入我的服务。 这是我的示例:

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

我使用Apache CXF实现,这是我对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>

我还使用Apache Karaf 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一起正常工作?

1 个答案:

答案 0 :(得分:0)

尝试使用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()