Rest Service and the HTTPServletReqeust Object

Today I got a strange problem with my REST service which needs a HttpServletRequest object to perform the RemoteUser name.

First I injected the HttpServletRequest as a field into my RestService-Class

....
@Path("/")
@Produces({ "text/html", "application/xml", "application/json" })
@Stateless
public class SystemRestService {
 ...   
	@javax.ws.rs.core.Context
	private static HttpServletRequest servletRequest;
.....

This works fine on my local glassfish server 3.1.1. But after I deployed this into my productive environment (glassfish 3.1) the field ‘servletRequest’ was always null.

The problem here is that injecting the HttpServletRequest into an instance field can become very soon stale. The solution is to annotating a method parameter to assure that the request object is obtained in connection to processing a request.

... 	
@GET
	@Path("/profile.json")
	@Produces("application/json")
	public String getUserByID(@QueryParam("uid") String user,
			@QueryParam("items") String items,@Context HttpServletRequest servletRequest) {
.....

See also this discussion on the coderanch:

http://www.coderanch.com/t/510941/Web-Services/java/Print-Client-IP#2649412

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.