jakarta-eejax-rs

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
}

Solution

  • 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.