简体   繁体   中英

how to inject headers in a `@context HttpServletRequest`?

Let's say I have this code:

@ApplicationPath("...")
public class MyApp extends ResourceConfig {
    public SalesLayerApplication() {
        this.register(HeaderInjecterFilter.class);
        this.register(Test.class);
    }
}

@PreMatching
public class HeaderInjecterFilter implements ContainerRequestFilter {
    @Override
    public void filter(final ContainerRequestContext crc) throws IOException {
        crc.getHeaders().add("foo", "bar");
    }
}

@Path("/test")
public class Test {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String dump(@Context final HttpServletRequest request) {
        return request.getHeader("foo");
    }
}

I was expecting to call the rest entry point /test and to retrieve the string bar .

But all I see is null

If I use @HeaderParam("foo") I correctly retrieve the variable, but I need to access throug the @Context HttpServletRequest .

Why would you expect that adding headers to the ContainerRequestContext would also add it to the HttpServletRequest? These are completely unrelated entities. Try injecting HttpHeaders or you can also inject the ContainerRequestContext directly.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM