Redirecting to a page using restful methods?

前端 未结 5 736
广开言路
广开言路 2021-02-14 11:36

I\'ve created a page which asks user to fill some form fields and when he submits, the form is sent to a Restful method which you can see below:

@POST
@Path(         


        
5条回答
  •  日久生厌
    2021-02-14 12:28

    It is not good idea to use the "WebApplicationException" in order to redirect the request. in Jersey (2.4.1) you should be able to redirect the request via the normal servlet way, (request.getServletContext().getRequestDispatcher().forward() or just response.sendRedirect())

    The following is how Jersey process the request

    org.glassfish.jersey.servlet.ServletContainer.service(HttpServletRequest request, HttpServletResponse response)
          requestScope.runInScope
               final ContainerResponse response = endpoint.apply(data)
                      methodHandler.invoke(resource, method, args);
               Responder.process(ContainerResponse);
    

    That methodHandler is your REST service class, method is the function in that service class.

    The step to redirect page become straitforward

    1. Get the (request, response) through Jersey injection (@Context HttpServletRequest request, @Context HttpServletResponse response) in class field or function parameter

    2. Call request.getServletContext().getRequestDispatcher() to get the dispatcher for "forward" or use Response.sendRedirect(url)

    Once you application is returned (just null), Jersey will try to process the result in the "Responder.process(ContainerResponse)". In this step, it will use response to set status (204 no contents for your null return).

    So the key point here is you must finalize/close response object before return from your service function. Otherwise, Jersey may overwrite your output.

    Small tips on why "WebApplicationException" can overwrite Jersey repsponse. It is because org.glassfish.jersey.server.ServerRuntime.mapException() will use the "webApplicationException.getResponse()" as the return response result.

提交回复
热议问题