2011-10-24 37 views
13

Tôi có thể truy cập đối tượng Yêu cầu HttpServlet trong dịch vụ web xà phòng như sau: Khai báo trường riêng cho WebServiceContext trong triển khai dịch vụ và chú thích nó dưới dạng tài nguyên:Truy cập đối tượng HttpServletRequest trong dịch vụ web an toàn

@Resource 
private WebServiceContext context; 

Để có được đối tượng HttpServletRequet, tôi viết code như sau:

MessageContext ctx = context.getMessageContext(); 
HttpServletRequest request =(HttpServletRequest)ctx.get(AbstractHTTPDestination.HTTP_REQUEST); 

Nhưng những điều này không làm việc trong một dịch vụ web yên tĩnh. Tôi đang sử dụng Apache CXF để phát triển dịch vụ web an toàn. Xin vui lòng cho tôi biết làm thế nào tôi có thể truy cập vào đối tượng HttpServletRequest.

Trả lời

14

tôi khuyên bạn nên sử dụng org.apache.cxf.jaxrs.ext.MessageContext

import javax.ws.rs.core.Context; 
import org.apache.cxf.jaxrs.ext.MessageContext; 

... 
// add the attribute to your implementation 
@Context 
private MessageContext context; 

... 
// then you can access the request/response/session etc in your methods 
HttpServletRequest req = context.getHttpServletRequest(); 
HttpServletResponse res = context.getHttpServletResponse() 

Bạn có thể sử dụng @Context chú thích để cờ các loại khác (chẳng hạn như ServletContext hoặc HttpServletRequest cụ thể). Xem Context Annotations.

+4

Trong việc thực hiện Jersey, 'MessageContext' không hoạt động. Nhưng bạn vẫn có thể sử dụng '@Context HttpServletRequest'. – kxsong

0

sử dụng mã này cho yêu cầu truy cập và phản ứng đối với từng yêu cầu:

@Path("/User") 
public class RestClass{ 

    @GET 
    @Path("/getUserInfo") 
    @Produces(MediaType.APPLICATION_JSON) 
    public Response getUserrDetails(@Context HttpServletRequest request, 
      @Context HttpServletResponse response) { 
     String username = request.getParameter("txt_username"); 
     String password = request.getParameter("txt_password"); 
     System.out.println(username); 
     System.out.println(password); 

     User user = new User(username, password); 

     return Response.ok().status(200).entity(user).build(); 
    } 
... 
} 
Các vấn đề liên quan