Redirecting to a page using restful methods?

2020-06-14 03:01发布

问题:

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("addUser")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void addUser(@FormParam("username") String username,
        @FormParam("password") String password,
        @FormParam("id") String id,
        @FormParam("group_name") String groupName,
        @FormParam("authority_name") String authorityName,
        @FormParam("authority_id") String authorityId
        )
{
    //Something will be done here
}


How can I redirect the user at the end of this function to (let's say) index.jsp?

回答1:

Create a URI using javax.ws.rs.core.UriBuilder that maps the parameters and other data you want to preserve. Then use Response.temporaryRedirect to return a redirect to the client and pass it the URI you’ve built.



回答2:

change your code like this, the addUser() should return a Response Object

public Response addUser(@FormParam("username") String username,
        @FormParam("password") String password,
        @FormParam("id") String id,
        @FormParam("group_name") String groupName,
        @FormParam("authority_name") String authorityName,
        @FormParam("authority_id") String authorityId
        )
{
    //Something will be done here

    java.net.URI location = new java.net.URI("../index.jsp?msg=A_User_Added");
    return Response.temporaryRedirect(location).build()

}


回答3:

Finally I come to this conclusion that there are no other way than what I did:
So here is my solution:

try {
        java.net.URI location = new java.net.URI("../index.jsp?msg=A_User_Added");
        throw new WebApplicationException(Response.temporaryRedirect(location).build());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }


By adding this block to my code, I got what I needed. Hope it helps you as well.



回答4:

See below the usage of redirecting in web services:

public class LoginWebService {

    @POST
    @Path("/check")
    public Response checkDetails(@FormParam("name") String name,@FormParam("pass") String pass ) throws URISyntaxException  {

        URI uri = new URI("/login/success");
        URI uri2= new URI("http://localhost:9090/NewWebServiceproject/new/login/failure");

        if(name.equals("admin") && pass.equals("pass"))
    //@Path("http://localhost:8010/NewWebServiceproject/new/login/success");
            {
            return Response.temporaryRedirect(uri).build();
            //Response.seeOther(uri);
            //return Response.status(200).entity("user successfully login").build();
            }
        else
        {
            return Response.temporaryRedirect(uri2).build();
            //Response.seeOther(uri2);
            //return Response.status(200).entity("user logon failed").build();
            }
    }
    @POST
    @Path("/success")
    public Response successpage()
    {
    return Response.status(200).entity("user successfully login").build();
    }
    @POST
    @Path("/failure")
    public Response failurepage()
    {
    return Response.status(200).entity("user logon failed").build();
    }
}


回答5:

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.