I am developing REST web services using Jersey and I need to call a servlet from web service methods to authenticate the user. I get exceptions when running the below code:
@Path("/server")
public class WebServer {
@Resource
private WebServiceContext context;
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) throws IOException, ServletException {
ServletContext servletContext = (ServletContext) context.getMessageContext()
.get(MessageContext.SERVLET_CONTEXT); // Here I am getting NPE
HttpServletRequest request = (HttpServletRequest) context.getMessageContext()
.get(MessageContext.SERVLET_REQUEST);
HttpServletResponse response = (HttpServletResponse) context.getMessageContext()
.get(MessageContext.SERVLET_RESPONSE);
request.setAttribute("username", track.getUsername());
request.setAttribute("password", track.getPassword());
servletContext.getRequestDispatcher("/LoginAction").include(request, response);
String loginStatus = request.getParameter("loginStatus");
String Token = request.getParameter("Token");
String result = ""+track;
return Response.status(200).entity(result).build();
}
}
The exception is:
java.lang.NullPointerException at
com.webservices.server.WebServer.createTrackInJSON(WebServer.java:36)
…servletContext is null
Please help me determine how to get the servlet context in a web service.
Use the @Context annotation, and inject the correct class. You can also directly inject the servlet request and response objects.