代码之家  ›  专栏  ›  技术社区  ›  Ruslan

将HttpServletRequest注入rest服务

  •  0
  • Ruslan  · 技术社区  · 7 年前

    我想通过将HttpServletRequest注入到我的服务中 @Context 下面是我的例子:

    @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>
    

    <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.ext org.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 回复  |  直到 7 年前
        1
  •  0
  •   Bhaskara Arani    7 年前

    尝试使用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()
    
    推荐文章