🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Overview
The @Context annotation can be used to inject any of the below instances into an instance field or directly into the resource method as a parameter.The object instances that it can inject are the following:
- SecurityContext – Security context instance for the current HTTP request
- Request – Used for setting precondition request processing
- Application, Configuration, and Providers -> Provide access to the JAX-RS application, configuration, and providers instances
- ResourceContext – Resource context class instances
- ServletConfig – The ServletConfig instance instance
- ServletContext – The ServletContext instance
- HttpServletRequest – The HttpServletRequest instance for the current request
- HttpServletResponse – The HttpServletResponse instance for the current request
- HttpHeaders – Maintains the HTTP header keys and values
- UriInfo – Query parameters and path variables from the URI called
Let's understand @Context annotation with examples.
2. HTTP headers
Although HTTP headers can be injected using the @HeaderParam annotation, JAX-RS also provides the facility of injecting an instance of the HttpHeaders interface (as an instance variable or method parameter). This is useful when you want to iterate over all possible headers rather than injecting a specific header value by name
@Path("testinject")
public class InjectURIDetails{
//localhost:8080/<root-context>/testinject/httpheaders
@GET
@Path("httpheaders")
public void test(@Context HttpHeaders headers){
System.out.println("ALL headers -- "+ headers.getRequestHeaders().toString());
System.out.println("'Accept' header -- "+ headers.getHeaderString("Accept"));
System.out.println("'TestCookie' value -- "+ headers.getCookies().get("TestCookie").getValue());
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllHttpHeaders(final @Context HttpHeaders httpHeaders){
return Response.ok(httpHeaders.getRequestHeaders()).build();
}
@GET
@Path("/{header-param}")
@Produces(MediaType.APPLICATION_JSON)
public Response getSpecifiedHeader(final @PathParam("header-param") String header_param,
final @Context HttpHeaders httpHeaders){
return Response.ok(httpHeaders.getRequestHeader(header_param)).build();
}
3. HTTP URI details
UriInfo is another interface whose instance can be injected by JAX-RS (as an instance variable or method parameter). Use this instance to fetch additional details related to the request URI and its parameters (query, path)
@Path("testinject")
public class InjectURIDetails{
//localhost:8080/<root-context>/testinject/uriinfo
@GET
@Path("uriinfo")
public void test(@Context UriInfo uriDetails){
System.out.println("ALL query parameters -- "+ uriDetails.getQueryParameters().toString());
System.out.println("'id' query parameter -- "+ uriDetails.getQueryParameters.get("id"));
System.out.println("Complete URI -- "+ uriDetails.getRequestUri());
}
}
4. HttpServletRequest Details
@Path("/remote-address")
public class HttpServletRequestResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getRemoteAddress(final @Context HttpServletRequest httpServletRequest){
return Response.ok(httpServletRequest.getRemoteAddr()).build();
}
}
5. More examples using @Context Annotations
@Path("/resource-context")
public class ResourceContextResource {
@GET
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
public Response get(final @Context ResourceContext resourceContext, final @Context UriInfo uriInfo) {
final CalculatorResource calculatorResource = resourceContext.getResource(CalculatorResource.class);
int x = Integer.valueOf(uriInfo.getQueryParameters().getFirst("x"));
int y = Integer.valueOf(uriInfo.getQueryParameters().getFirst("y"));
return Response.ok(calculatorResource.add(x, y)).build();
}
}
@Path("/security-context")
public class SecurityContextResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response sayHello(final @Context SecurityContext securityContext) {
return Response.ok(securityContext.isUserInRole("guest")).build();
}
}
@Path("servlet-config")
public class ServletConfigResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getServletName(final @Context ServletConfig servletConfig){
return Response.ok(servletConfig.getServletName()).build();
}
}
@Path("servlet-context")
public class ServletContextResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getContextPath(final @Context ServletContext servletContext) {
return Response.ok(servletContext.getContextPath()).build();
}
}
6. Conclusion
This post explained the important @Context JAX-RS annotation.Learn more about Jersey Rest framework on Jersey Rest Developer Guide.
All the code of this article is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment