I want ot inject HttpServletRequest into my service via @Context
annotation. Here is my example:
@Path("/")
public class MyService {
@Context
private HttpServletRequest request;
}
I use Apache CXF implementation and here are my dependencies from 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>
Also I use Apache Karaf OSGI container for deploying and that's why my app is a bundle packaging type. There is configuration for that:
<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>
Without javax.ws.rs.ext
and org.apache.cxf.jaxrs.impl.tl
in import-package section I got one of these exceptions:
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
So now I have a follow exception when try to deploy my app:
Caused by: java.lang.IllegalArgumentException: Can not set javax.servlet.http.HttpServletRequest field MyService.request to org.apache.cxf.jaxrs.impl.tl.ThreadLocalHttpServletRequest
And I spent a lot of time to figure out what's the problem.. But one thing I note:
if I use ThreadLocalHttpServletRequest request
instead of HttpServletRequest request
, then it works without exceptions, but the request
field is null
when I try to use it from any methods.
What should I do to make it works properly with HttpServletReqest
?
try to use 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.