Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to JSF page from JAX-RS method?

I have a JAX-RS resource and after resolve business logic I want to show the results in a JSF page. How can I do that?

@Path("/rest")
public class PaymentServiceRest {

    @GET
    @Path("/status")
    public String method()  {

        // Business logic...

        return "results.xhtml"; // how to return a jsf page? 
    }
}

The first time the client access the app is using the url, i.e: http://myApp/rest/status, then do some logic and based on that do a redirection.

like image 336
Sergio Avatar asked Oct 20 '13 19:10

Sergio


1 Answers

Well, I've found a way to forward from a JAX-RS method to a JSF page:

@GET
@Path("/test")
@Produces("text/html")
public Response test(@Context ServletContext context,
        @Context HttpServletRequest request,
        @Context HttpServletResponse response) {

    try {
        String myJsfPage = "/response.xhtml";
        context.getRequestDispatcher(myJsfPage).forward(request, response);
    } catch (ServletException | IOException ex) {
        return Response.status(NOT_FOUND).build();
    }
    return null;
}

As described here: https://www.java.net//forum/topic/glassfish/glassfish/forwarding-jsf-jax-rs

The injection via the method can also be done via injection in fields, that is a matter of 'preference'

This have been tested in TomEE (Apache CXF). I'm just a little curious if this is just a dirty "hack" or if there is a better way to do it.


UPDATE

I found a better way to redirect that renders the JSF tags without any issues (in my case tags such as <p:graphicImage/> were not rendering properly)

@GET
@Path("/test")
@Produces("text/html")
public Response test(@Context HttpServletRequest request, @Context HttpServletResponse response)
        throws IOException {
    String myJsfPage = "/response.xhtml";
    String contextPath = request.getContextPath();
    response.sendRedirect(contextPath + myJsfPage);
    return Response.status(Status.ACCEPTED).build();
}
like image 161
Sergio Avatar answered Oct 26 '22 15:10

Sergio