Jersey URL forwarding

廉价感情. 提交于 2019-12-09 11:40:20

问题


Inside a Jersey REST method I would like to forward to an another website. How can I achieve that?

@Path("/")
public class News {

    @GET
    @Produces(MediaType.TEXT_HTML)
    @Path("go/{news_id}")
    public String getForwardNews(
        @PathParam("news_id") String id) throws Exception {

        //how can I make here a forward to "http://somesite.com/news/id" (not redirect)?

        return "";
    }
}

EDIT:

I'm getting the No thread local value in scope for proxy of class $Proxy78 error when trying to do something like this:

@Context
HttpServletRequest request;
@Context
HttpServletResponse response;
@Context
ServletContext context;

...

RequestDispatcher dispatcher =  context.getRequestDispatcher("url");
dispatcher.forward(request, response);

回答1:


public Response foo()
{
    URI uri = UriBuilder.fromUri(<ur url> ).build();
    return Response.seeOther( uri ).build();
}

I used above code in my application and it works.




回答2:


Try this, it worked for me:

public String getForwardNews(

@Context final HttpServletRequest request,

@Context final HttpServletResponse response) throws Exception

{

System.out.println("CMSredirecting... ");

response.sendRedirect("YourUrlSite");

return "";

}



回答3:


I can't test it right now. But why not...

Step 1. Get access to HttpServletResponse. To do it declare in your service something like:

@Context
HttpServletResponse _currentResponse;

Step 2. make redirect

...
_currentResponse.sendRedirect(redirect2Url);

EDIT

Well, to call forward method you need get to ServletContext. It is can be resolved the same way as response:

@javax.ws.rs.core.Context 
ServletContext _context;

Now _context.forward is available



来源:https://stackoverflow.com/questions/8242719/jersey-url-forwarding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!