简体   繁体   中英

What is @javax.ws.rs.core.Context

First of all, I am very new to this topic and not sure if its a very basic question. I couldnt help but posting here.

I am looking at a code that uses restful webservice. An ajax call is being made inorder to provide details to this ws. The method signature looks like this:

@Path("/issues")
@GET
public Response getIssueCockpit(@javax.ws.rs.core.Context HttpServletRequest paramHttpServletRequest, @QueryParam("filterGlobal") String paramString) throws Exception 
{ 
    //Code here
}

I understand that the webservice caller calls this API using "eg: http://app/resource/issues1 " and this method gets called.

  1. Can you please help me understand what is @javax.ws.rs.core.Context HttpServletRequest paramHttpServletRequest in the below method call.
  2. What does the annotation do in this case.
  3. An ajax call is being made to provide details to this WS> How is the context preserved in the ServletRequest.

Thanks for the help

If you've worked with an dependency injection frameworks like Spring or CDI, you'll see that in order to let the framework inject a dependency, you need a marker annotation. In Spring you would see @Autowired or @Inject , in CDI you would see @Inject . @Context works the same way. In order for the JAX-RS runtime to know that HttpServletRequest is to be injected, it needs to be annotated with @Context . Same way JAX-RS knows to inject the query parameter is through the @QueryParam annotation.

The HttpServletRequest is from the servlet container. When a request comes the container creates the HttpServletRequest and passes it down to servlet implementations. The JAX-RS runtime hands this object to your resource method/class, if it sees that you want it, by annotating it.

The HttpServletRequest object represents the HTTP request from the browser or client application. So a call to " http://app/resource/issues1 " is represented by an instance of the HttpServletRequest . This object has methods that report information about the request such as the Http headers, Media type, and the request body.

The annotation @Context injects (just like @Autowired from Spring and @Inject from Java EE) the HttpServletRequest instance for the request made to the path ( /issue ) with HTTP method type ( GET ). In fact, the @Context annotation can inject a vast number of very useful objects related to the request. See the full list below:

The ServletRequest lives for as long as the request exists. This is normally very short-lived so for the duration of the request the ServletRequest is maintaining.

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