How to create Object in the class implementing HandlerInterceptor to access it from anywhere for that reqest












0














I am having situation like: in the preHandle() method of the class implementing HandlerInterceptor, i am having sessionId getting in the incoming HttpServletRequest object request. now using this session id i am fetching userInfo from the DB. the same info i have to use somewhere else like service layer to process the request.



It would be very helpful if anyone of you help me out to achieve it. Thanks in advance.










share|improve this question



























    0














    I am having situation like: in the preHandle() method of the class implementing HandlerInterceptor, i am having sessionId getting in the incoming HttpServletRequest object request. now using this session id i am fetching userInfo from the DB. the same info i have to use somewhere else like service layer to process the request.



    It would be very helpful if anyone of you help me out to achieve it. Thanks in advance.










    share|improve this question

























      0












      0








      0







      I am having situation like: in the preHandle() method of the class implementing HandlerInterceptor, i am having sessionId getting in the incoming HttpServletRequest object request. now using this session id i am fetching userInfo from the DB. the same info i have to use somewhere else like service layer to process the request.



      It would be very helpful if anyone of you help me out to achieve it. Thanks in advance.










      share|improve this question













      I am having situation like: in the preHandle() method of the class implementing HandlerInterceptor, i am having sessionId getting in the incoming HttpServletRequest object request. now using this session id i am fetching userInfo from the DB. the same info i have to use somewhere else like service layer to process the request.



      It would be very helpful if anyone of you help me out to achieve it. Thanks in advance.







      spring-mvc spring-security






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 at 15:18









      Rohit

      146




      146
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You can use a ThreadLocal to store a reference to a user that will only be accessible to the current thread of execution.



          https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html



          You can wrap this in a context class so that in your service you can access the current user via the static call: User user = UserContextUtils.getUser();



          UserContextUtils:



          public class UserContextUtils {

          private static final ThreadLocal<User> CONTEXT = new ThreadLocal<>();

          public static void setUser(User user) {
          CONTEXT.set(user);
          }

          public static User getUser() {
          return CONTEXT.get();
          }

          public static void clear() {
          CONTEXT.remove();
          }
          }


          The Interceptor:



          public class MyHandlerInterceptor implements HandlerInterceptor {

          @Override
          public boolean preHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler)
          throws Exception {

          User user = null;// get user from the database.
          UserContextUtils.setUser(user);

          return true;
          }

          @Override
          public void afterCompletion(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          Exception ex) {

          // as some web servers re-use threads, you must ensure that the
          // context is cleared on completion either here or elsewhere.

          UserContextUtils.clear();
          }

          @Override
          public void postHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          ModelAndView modelAndView) throws Exception {

          }
          }





          share|improve this answer





















          • Thanks a lot Alan. it worked for me :)
            – Rohit
            Nov 21 at 4:41











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396134%2fhow-to-create-object-in-the-class-implementing-handlerinterceptor-to-access-it-f%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You can use a ThreadLocal to store a reference to a user that will only be accessible to the current thread of execution.



          https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html



          You can wrap this in a context class so that in your service you can access the current user via the static call: User user = UserContextUtils.getUser();



          UserContextUtils:



          public class UserContextUtils {

          private static final ThreadLocal<User> CONTEXT = new ThreadLocal<>();

          public static void setUser(User user) {
          CONTEXT.set(user);
          }

          public static User getUser() {
          return CONTEXT.get();
          }

          public static void clear() {
          CONTEXT.remove();
          }
          }


          The Interceptor:



          public class MyHandlerInterceptor implements HandlerInterceptor {

          @Override
          public boolean preHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler)
          throws Exception {

          User user = null;// get user from the database.
          UserContextUtils.setUser(user);

          return true;
          }

          @Override
          public void afterCompletion(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          Exception ex) {

          // as some web servers re-use threads, you must ensure that the
          // context is cleared on completion either here or elsewhere.

          UserContextUtils.clear();
          }

          @Override
          public void postHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          ModelAndView modelAndView) throws Exception {

          }
          }





          share|improve this answer





















          • Thanks a lot Alan. it worked for me :)
            – Rohit
            Nov 21 at 4:41
















          0














          You can use a ThreadLocal to store a reference to a user that will only be accessible to the current thread of execution.



          https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html



          You can wrap this in a context class so that in your service you can access the current user via the static call: User user = UserContextUtils.getUser();



          UserContextUtils:



          public class UserContextUtils {

          private static final ThreadLocal<User> CONTEXT = new ThreadLocal<>();

          public static void setUser(User user) {
          CONTEXT.set(user);
          }

          public static User getUser() {
          return CONTEXT.get();
          }

          public static void clear() {
          CONTEXT.remove();
          }
          }


          The Interceptor:



          public class MyHandlerInterceptor implements HandlerInterceptor {

          @Override
          public boolean preHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler)
          throws Exception {

          User user = null;// get user from the database.
          UserContextUtils.setUser(user);

          return true;
          }

          @Override
          public void afterCompletion(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          Exception ex) {

          // as some web servers re-use threads, you must ensure that the
          // context is cleared on completion either here or elsewhere.

          UserContextUtils.clear();
          }

          @Override
          public void postHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          ModelAndView modelAndView) throws Exception {

          }
          }





          share|improve this answer





















          • Thanks a lot Alan. it worked for me :)
            – Rohit
            Nov 21 at 4:41














          0












          0








          0






          You can use a ThreadLocal to store a reference to a user that will only be accessible to the current thread of execution.



          https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html



          You can wrap this in a context class so that in your service you can access the current user via the static call: User user = UserContextUtils.getUser();



          UserContextUtils:



          public class UserContextUtils {

          private static final ThreadLocal<User> CONTEXT = new ThreadLocal<>();

          public static void setUser(User user) {
          CONTEXT.set(user);
          }

          public static User getUser() {
          return CONTEXT.get();
          }

          public static void clear() {
          CONTEXT.remove();
          }
          }


          The Interceptor:



          public class MyHandlerInterceptor implements HandlerInterceptor {

          @Override
          public boolean preHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler)
          throws Exception {

          User user = null;// get user from the database.
          UserContextUtils.setUser(user);

          return true;
          }

          @Override
          public void afterCompletion(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          Exception ex) {

          // as some web servers re-use threads, you must ensure that the
          // context is cleared on completion either here or elsewhere.

          UserContextUtils.clear();
          }

          @Override
          public void postHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          ModelAndView modelAndView) throws Exception {

          }
          }





          share|improve this answer












          You can use a ThreadLocal to store a reference to a user that will only be accessible to the current thread of execution.



          https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html



          You can wrap this in a context class so that in your service you can access the current user via the static call: User user = UserContextUtils.getUser();



          UserContextUtils:



          public class UserContextUtils {

          private static final ThreadLocal<User> CONTEXT = new ThreadLocal<>();

          public static void setUser(User user) {
          CONTEXT.set(user);
          }

          public static User getUser() {
          return CONTEXT.get();
          }

          public static void clear() {
          CONTEXT.remove();
          }
          }


          The Interceptor:



          public class MyHandlerInterceptor implements HandlerInterceptor {

          @Override
          public boolean preHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler)
          throws Exception {

          User user = null;// get user from the database.
          UserContextUtils.setUser(user);

          return true;
          }

          @Override
          public void afterCompletion(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          Exception ex) {

          // as some web servers re-use threads, you must ensure that the
          // context is cleared on completion either here or elsewhere.

          UserContextUtils.clear();
          }

          @Override
          public void postHandle(HttpServletRequest request,
          HttpServletResponse response, Object handler,
          ModelAndView modelAndView) throws Exception {

          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 19:09









          Alan Hay

          15.2k22769




          15.2k22769












          • Thanks a lot Alan. it worked for me :)
            – Rohit
            Nov 21 at 4:41


















          • Thanks a lot Alan. it worked for me :)
            – Rohit
            Nov 21 at 4:41
















          Thanks a lot Alan. it worked for me :)
          – Rohit
          Nov 21 at 4:41




          Thanks a lot Alan. it worked for me :)
          – Rohit
          Nov 21 at 4:41


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396134%2fhow-to-create-object-in-the-class-implementing-handlerinterceptor-to-access-it-f%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Create new schema in PostgreSQL using DBeaver

          Deepest pit of an array with Javascript: test on Codility

          Fotorealismo