2011-11-23 34 views
7

Bên trong phương thức REST REST Tôi muốn chuyển tiếp đến một trang web khác. Làm thế nào tôi có thể đạt được điều đó?Chuyển tiếp URL Jersey

@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:

Tôi nhận được lỗi No thread local value in scope for proxy of class $Proxy78 khi cố gắng để làm một cái gì đó như thế này:

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

... 

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

Trả lời

2

tôi không thể kiểm tra nó ngay bây giờ. Nhưng tại sao không ...

Bước 1. Truy cập vào HttpServletResponse. Để làm điều đó tuyên bố trong một cái gì đó dịch vụ của bạn như:

@Context 
HttpServletResponse _currentResponse; 

Bước 2. làm chuyển hướng

... 
_currentResponse.sendRedirect(redirect2Url); 

EDIT

Vâng, để gọi về phía trước phương pháp bạn cần có được để ServletContext. Người ta có thể được giải quyết một cách tương tự như phản ứng:

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

Bây giờ _context.forward có sẵn

+0

Tôi quan tâm đến chuyển tiếp, không chuyển hướng. –

+0

@DorinGrecu chỉ cần thêm cách truy cập vào ngữ cảnh – Dewfy

+0

@Derwy Vui lòng xem câu hỏi đã chỉnh sửa của tôi, nó không hoạt động ngay lập tức. –

3

Hãy thử điều này, nó làm việc cho tôi:

public String getForwardNews(

@Context final HttpServletRequest request, 

@Context final HttpServletResponse response) throws Exception 

{ 

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

response.sendRedirect("YourUrlSite"); 

return ""; 

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

tôi đã sử dụng trên mã trong tôi ứng dụng và nó hoạt động.

+1

Bạn có thể sử dụng Response.temporaryRedirect (vị trí) .build(); xem ví dụ đầy đủ tại đây http://www.javaproficiency.com/2015/04/redirect-in-jersey.html –

+0

http://stackoverflow.com/a/25332038/419348 'seeOther' là một loại khác với' temporaryRedirect '. Một là '301', và một là' 302'. – AechoLiu

+1

Đây là chuyển hướng không chuyển tiếp. – Monir