0

Using Jersey 2.x how would I inject HttpRequest and HttpSession objects? And how to use injected request and Httpsession object in a service class?

  1. in jersey 2.x injected request and session objects in Resource class working fine getting request and session objects

  2. out side like business class not working.

TechnicalTophat
  • 1,655
  • 1
  • 15
  • 37
Suresh
  • 1

1 Answers1

1

You can try adding @Context HttpServletRequest request to your resources method signature. That will make request available for the duration of the method.

It's not good practice to pass HttpServeltRequest / Session objects down to service or business classes. If you do this, you make it very difficult to use the service class in anything but a Web Application. You should pull the data that the service class requires out of the HttpServletRequest / Session in the Resource class and pass it to service class

For example, if your service class needs access to the userName that is held in an HttpServletRequests "userName" parameter, then the Resource class should do

String userName = req.getParameter("UserName");
serviceClass.doSomething(userName);

rather than

serviceClass.doSomething(req);
DaveH
  • 7,187
  • 5
  • 32
  • 53
  • Note that in jersey with grizzly server, it is not possible to inject ``HttpServletRequest``, as it will be null. Please see http://stackoverflow.com/questions/37167921/get-client-ip-in-jersey-2-22-2/#answer-37168839 – Alexandre Cartapanis Jun 20 '16 at 12:39
  • @AlexandreCartapanis [that's not true](http://stackoverflow.com/a/33684719/2587435) – Paul Samsotha Jun 20 '16 at 14:59
  • @AlexandreCartapanis Can I ask if you downvoted on the basis of your assertion about Grizzly? The OP makes no mention of Grizzly in the question so if you did downvote, your downvote relates to a question that the OP didn't ask – DaveH Jun 20 '16 at 18:50
  • @DaveH you are right, i tried to cancel the downvote but it not possible as it is 6 hours ago (saying "You last voted on this answer 6 hours ago. Your vote is now locked in unless this answer is edited.")... Maybe you can edit your anwser so i can cancel it ? – Alexandre Cartapanis Jun 20 '16 at 19:22