Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get access to the HttpServletRequest object when using Java Web Services

I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to not get null for the WebServiceContext.

In other words: how can I execute the following line to get a non-null value for wsCtxt?

MessageContext msgCtxt = wsCtxt.getMessageContext();

@WebService
public class MyService{

  @Resource
  WebServiceContext wsCtxt;

  @WebMethod
  public void myWebMethod(){
    MessageContext msgCtxt = wsCtxt.getMessageContext();
    HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
    String clientIP = req.getRemoteAddr();
  }
like image 801
Steve McLeod Avatar asked Sep 25 '08 13:09

Steve McLeod


People also ask

How do I pass HttpServletRequest in Java?

Pass it to the constructor: public class XmlParser{ final private HttpServletRequest request; public XmlParser(HttpServletRequest request) { this. request = request; } // use it in othe methods... }

What is HttpServletRequest in Java?

The HttpServletRequest provides methods for accessing parameters of a request. The type of the request determines where the parameters come from. In most implementations, a GET request takes the parameters from the query string, while a POST request takes the parameters from the posted arguments.

How HttpServletRequest object is created?

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods ( doGet , doPost , etc). String identifier for Basic authentication. String identifier for Client Certificate authentication.


1 Answers

I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The J2ee tutorial on @Resource indicates that the name of the variable is used as part of the lookup. I've encountered this same problem using resource injection in Glassfish injecting a different type of resource.

Though your correct name may not be wsContext. I'm following this java tip. If you like the variable name wsCtxt, then use the name attribute in the variable declaration:

@Resource(name="wsContext") WebServiceContext wsCtxt;

like image 156
James A Wilson Avatar answered Oct 06 '22 23:10

James A Wilson