Enterprise Java

What is javax.ws.rs.core.context? [ Part 4 ]

How to use the @Context annotation

In part 3 of What is javax.ws.rs.core.context? you learned how to use the @Context annotation with Request and Configuration, Providers, and Application instances.

In this article, you will learn about using the @Context annotation to inject the HttpServletResponse and the HttpServletRequest classes.

Get Access to the HttpServletRequest Properties

The JAX-RS API runs on top of Servlets and therefore instances of servlet objects are available to the JAX-RS resource. The @Context annotation is used to inject the HttpServletRequest instance for the current request. Its methods give access to detailed information about the request.

Let’s look at a simple example that retrieves the request’s remote address.

@Path("/remote-address")
public class HttpServletRequestResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getRemoteAddress(
                 final @Context HttpServletRequest httpServletRequest){
        return Response.ok(httpServletRequest.getRemoteAddr()).build();
    }

}

In this code example, the Servlet request object is injected into the method parameter httpServletRequest by the @Context annotation. The getRemoteAddr() method is called and returns the IP address of the server that made the request.

If you are running this example on a local machine the response from calling the URL http://localhost:8080/rest-server/remote-address will be 127.0.0.1.

Get Access to the HttpServletResponse Properties

Just as you can obtain an instance of the HttpServletRequest object you can also get the HttpServletResponse instance and call its methods and set values on the response instance.

Let’s have a look at an example that gets the ServletOutputStream and flush a message to the response.

@Path("/output")
public class HttpServletResponseResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(
                 final @Context HttpServletResponse httpServletResponse) 
                 throws IOException {

        ServletOutputStream out = httpServletResponse.getOutputStream();
        out.print("Hello");
        out.flush();

        return Response.ok().build();
    }
}

In this example, the HttpServletResponse object instance is injected into the method parameter httpServletResponse and then an instance of the ServletOutputStream object is obtained. I then use this object to write a message to the output stream and then flush it to the response.

If you visit the URL http://localhost:8080/rest-server/output you will see the message “Hello” printed to the screen.

Code Repository

The source code for this and all my articles are in the readlearncode_articles Github repository.

What Next?

That is all for part 4, in part 5 of What is javax.ws.rs.core.context? you will learn how to use the @Context annotation to inject instances of javax.servlet.ServletConfig and javax.servlet.ServletContext.

Java EE Video Course

If you are just starting out and are new to Java EE it can be pretty confusing to get your head around all the APIs. That is why I produced the video course Learning Java Enterprise Edition. During this two-hour course, you will meet all the most important Java EE APIs. With plenty of code examples and demonstrations on how to develop with Java EE, you will soon be on your way to being a Java EE developer.

After the introduction course, you will want to dive deeper into each APIs. There are courses for that as well. You can advance your knowledge of Java EE by learning how to construct RESTful endpoints using the JAX-RS API, then you can learn how to develop a chat application with the WebSocket API and then master JSON with the JSON-Processing API course. Many more courses on the road map, so why not jump in now and give your Java EE career a kick.

Further Reading

I have recently posted a mini-series of blogs taking a look at JAX-RS. They are published on readlearncode.com and discuss how to manage bean validation failure, work with Consumers and Producers, and how to create JAX-RS Resource Entities.

Reference: What is javax.ws.rs.core.context? [ Part 4 ] from our JCG partner Alex Theedom at the Read Learn Code blog.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button