I recently went through restful web services tutorial, but couldn't understand what a context is. Can someone explain what it it and also what @Context does?
For an explanation about context in programming terms, have a look at this answer. The JAX-RS API provides a @Context annotation. In general, such annotation can be used to obtain contextual Java types related to the request or response. Those types can be injected into classes managed by the JAX-RS runtime.
October 2020) Representational state transfer (REST) is a software architectural style that describes a uniform interface between physically separate components, often across the Internet in a client-server architecture. REST defines four interface constraints: Identification of resources. Manipulation of resources.
A Context object contains a list of properties in the form of NamedValue objects. These properties represent information about the client, the environment, or the circumstances of a request and generally are properties that might be inconvenient to pass as parameters.
Put simply, there are no differences between REST and RESTful as far as APIs are concerned. REST is the set of constraints. RESTful refers to an API adhering to those constraints. It can be used in web services, applications, and software.
JAX-RS provides the @Context
annotation to inject 12 object instances related to the context of the HTTP request and they are:
It is a little confusing to have both an @Inject
(or @Autowired
in Spring) and @Context
that does the same job, but it is hoped to bring more alignment to Java EE in the next edition. In the meantime, you will have to make do.
An interesting feature is that all of these instances can be injected as a field value or directly into the resource method.
An example of injection into the resource method parameter list:
@Path("/")
public class EndpointResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllHttpHeaders(final @Context HttpHeaders httpHeaders){
// Code here that uses httpHeaders
}
}
An example of injection into a field:
@Path("/")
public class EndpointResource {
private final @Context HttpHeaders httpHeaders;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllHttpHeaders(){
// Code here that uses httpHeaders
}
}
If you want to know more, take a look at this series of articles answering the question What is @Conext in JAX-RS used for?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With