我目前正在尝试在Quarkus 1.13中注入并读取HttpRequest,但没有成功。我使用RESTEasy Reactive作为我的端点。
这就是我目前包括的方式
@Path("/users/{id}")
class UserController(
@Inject val service: UserService,
@Context val httpRequest: io.vertx.core.http.HttpServerRequest,
)
...
构建过程成功了,但当我尝试访问像httpRequest.absoluteURI()
这样的属性时,我得到了一个NPE
java.lang.NullPointerException: Cannot invoke "org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext.serverRequest()" because the return value of "org.jboss.resteasy.reactive.server.core.CurrentRequestManager.get()" is null
at io.quarkus.resteasy.reactive.server.runtime.QuarkusContextProducers.httpServerRequest(QuarkusContextProducers.java:26)
at io.quarkus.resteasy.reactive.server.runtime.QuarkusContextProducers_Subclass.httpServerRequest$$superaccessor3(QuarkusContextProducers_Subclass.zig:451)
at io.quarkus.resteasy.reactive.server.runtime.QuarkusContextProducers_Subclass$$function$$3.apply(QuarkusContextProducers_Subclass$$function$$3.zig:29)
...
我还尝试了其他类,如io.vertx.mutiny.core.http.HttpServerRequest
或java.net.http.HttpRequest
,但仍然没有成功。用@Inject
注入它甚至没有构建。我错过了HttpServletRequest
类:/
有人有主意吗?
您有几个选项:
使用HttpFilter:https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpFilter.html
@WebFilter(urlPatterns = "/*")
public class FilterEverything extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
//Do something with HttpServletRequest
}
}
使用ContainerRequestFilter:https://docs.oracle.com/javaee/7/api/javax/ws/rs/container/ContainerRequestFilter.html
Quarkus文档展示:
@Provider
public class LoggingFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(LoggingFilter.class);
@Context
UriInfo info;
@Context
HttpServerRequest request;
@Override
public void filter(ContainerRequestContext context) {
//Do whatever you want
}
}
作为方法签名的一部分:
@GET
@Path("/someEndPoint")
@Produces("application/json")
public JsonObject getData(@PathParam("owner") String owner, @Context HttpServletRequest request) {
//Do something here
}