DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Circuit Breaker Pattern With Netflix-Hystrix: Java

Trending

  • Why Vulnerability Management Fails Without Reliable Asset Data
  • Solving Comprehension Debt in AI-Generated Codebases
  • PII Detection Before RAG Ingestion: Screening Documents in C#
  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. What Is javax.ws.rs.core.context? (Part 4)? [Snippets]

What Is javax.ws.rs.core.context? (Part 4)? [Snippets]

Continuing with our journey of the @Context annotation, let's see how you can inject Servlet request and response classes into your Java EE projects.

By 
Alex Theedom
·
Sep. 01, 17 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

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.

Requests Object (computer science) Spring Framework Annotation Repository (version control) Property (programming) application workplace GitHub

Published at DZone with permission of Alex Theedom. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Circuit Breaker Pattern With Netflix-Hystrix: Java

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook