9

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);
Don Grem
  • 1,257
  • 3
  • 17
  • 25

3 Answers3

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

Ajai S
  • 99
  • 1
  • 2
  • 1
    You can use Response.temporaryRedirect(location).build(); see full example here http://www.javaproficiency.com/2015/04/redirect-in-jersey.html – Anuj Dhiman Aug 15 '16 at 10:49
  • http://stackoverflow.com/a/25332038/419348 `seeOther` is some kind different with `temporaryRedirect`. One is `301`, and one is `302`. – AechoLiu May 17 '17 at 08:02
  • 2
    This is redirect not forward. – Monir May 24 '17 at 19:52
3

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 "";

}
Stedy
  • 7,359
  • 14
  • 57
  • 77
user2167877
  • 1,676
  • 1
  • 14
  • 15
2

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

Dewfy
  • 23,277
  • 13
  • 73
  • 121