ps0604
ps0604

Reputation: 1071

JAX-RS: performing an action after sending the response to the browser

My objective is to perform an action after the RestFul service returns the response.

I have the method below, but not sure when to do the action as once the method returns I have no control. Any ideas?

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/somepath")
public javax.ws.rs.core.Response someMethod (final RequestObject req) {

    // some actions

    return javax.ws.rs.core.Response.status(200).entity("response").build();

   //  here I would like to perform an action after the response is sent to the browser
}

Upvotes: 1

Views: 754

Answers (1)

BalusC
BalusC

Reputation: 1108722

You can't. Java doesn't work that way.

Just trigger an @Asynchronous service call. It'll immediately "fire and forget" a separate thread.

@EJB
private SomeService someService;

@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Path("/somepath")
public Response someMethod(RequestObject request) {
    // ...

    someService.someAsyncMethod();
    return Response.status(200).entity("response").build();
}
@Stateless
public class SomeService {

    @Asynchronous
    public void someAsyncMethod() { 
        // ...
    }

}

An alternative is a servlet filter.

Upvotes: 4

Related Questions