Pass value to injected EJBIs Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesHow to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?Should I use @EJB or @InjectHow to pass caller's info from web tier to EJB tier?HttpSession CDI injection in servlet projectInject @SessionScoped CDI Bean to @Stateless EJBHow to inject a Stateless Session Bean into a Message Driven Bean?If we inject a SessionScoped bean into a Stateless bean, what happens if there is no HTTP session?

Table alignment (make the content centre)

Would someone mind just getting me started with my Russian homework?

Was there an original & definitive use of alternate dimensions/realities in fiction?

Different past tense for various *et words

What is the motivation behind designing a control stick that does not move?

Am I required to correct my opponent's assumptions about my morph creatures?

Function of the separated, individual solar cells on Telstar 1 and 2? Why were they "special"?

Can authors email you PDFs of their textbook for free?

How to find better food in airports

Turn off Google Chrome's Notification for "Flash Player will no longer be supported after December 2020."

What is causing gaps in logs?

Can my UK debt be collected because I have to return to US?

Quick Slitherlink Puzzles: KPK and 123

Doesn't the concept of marginal utility speak to a cardinal utility function?

Could a simple hospital oxygen mask protect from aerosol poison?

Replace a motion-sensor/timer with simple single pole switch

To minimize the Hausdorff distance between convex polygonal regions

Tasha's Hideous Laughter used on a deaf person?

What happens if you just start drawing from the Deck of Many Things without declaring any number of cards?

Heuristic argument for the Riemann Hypothesis

How can I store milk for long periods of time?

Calculate Landau's function

Is Borg adaptation only temporary?

Is it good practice to speed up and slow down where not written in a song?



Pass value to injected EJB


Is Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesHow to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?Should I use @EJB or @InjectHow to pass caller's info from web tier to EJB tier?HttpSession CDI injection in servlet projectInject @SessionScoped CDI Bean to @Stateless EJBHow to inject a Stateless Session Bean into a Message Driven Bean?If we inject a SessionScoped bean into a Stateless bean, what happens if there is no HTTP session?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have an EJB application that consists of two beans, ServiceEJB (web tier) and BusinessEJB (business tier), where BusinessEJBis injected in ServiceEJB.



ServiceEJBreceives HTTP requests from the browser, calls a method in BusinessEJB, gets the result, and sends the HTTP response.



Also, ServiceEJB has access to the HttpSession object, where the userId of the user that logged in is stored. BusinessEJBdoes NOT have access to the HttpSession object.



The application needs to log messages (using sl4j/logback, for example). It could log the message in ServiceEJBor BusinessEJB methods, and when it logs a message, it has to include the userId of the session in the log entry.



Since BusinessEJB doesn't have the userId, it needs to get it from ServiceEJB. The question is what is the best way to achieve that. What I DON'T want to do is to add a userId field to each method in BusinessEJB as a parameter, as there are many ServiceEJBs and BusinessEJBs in the application (and other beans called by BusinessEJB that also generate log entries), and I don't want to pollute the application with the userId field. Instead, I could have a userId field at the EJB level, but how to populate them? Is there a way to achieve this with annotations? Any suggestions will be welcome.



@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Stateless
public class ServiceEJB

@Context
HttpServletRequest httpRequest;

@Inject
private BusinessEJB bean;

private String userId;

@Path("someurl")
public Response someMethod1()
final HttpSession session = httpRequest.getSession();
// get the userId from the session

String s = bean.someMethod2();

// return Response



@Stateless
public class BusinessEJB

private String userId;

public String someMethod2()
// .... log an entry with userId
return "something";











share|improve this question
































    0















    I have an EJB application that consists of two beans, ServiceEJB (web tier) and BusinessEJB (business tier), where BusinessEJBis injected in ServiceEJB.



    ServiceEJBreceives HTTP requests from the browser, calls a method in BusinessEJB, gets the result, and sends the HTTP response.



    Also, ServiceEJB has access to the HttpSession object, where the userId of the user that logged in is stored. BusinessEJBdoes NOT have access to the HttpSession object.



    The application needs to log messages (using sl4j/logback, for example). It could log the message in ServiceEJBor BusinessEJB methods, and when it logs a message, it has to include the userId of the session in the log entry.



    Since BusinessEJB doesn't have the userId, it needs to get it from ServiceEJB. The question is what is the best way to achieve that. What I DON'T want to do is to add a userId field to each method in BusinessEJB as a parameter, as there are many ServiceEJBs and BusinessEJBs in the application (and other beans called by BusinessEJB that also generate log entries), and I don't want to pollute the application with the userId field. Instead, I could have a userId field at the EJB level, but how to populate them? Is there a way to achieve this with annotations? Any suggestions will be welcome.



    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Stateless
    public class ServiceEJB

    @Context
    HttpServletRequest httpRequest;

    @Inject
    private BusinessEJB bean;

    private String userId;

    @Path("someurl")
    public Response someMethod1()
    final HttpSession session = httpRequest.getSession();
    // get the userId from the session

    String s = bean.someMethod2();

    // return Response



    @Stateless
    public class BusinessEJB

    private String userId;

    public String someMethod2()
    // .... log an entry with userId
    return "something";











    share|improve this question




























      0












      0








      0








      I have an EJB application that consists of two beans, ServiceEJB (web tier) and BusinessEJB (business tier), where BusinessEJBis injected in ServiceEJB.



      ServiceEJBreceives HTTP requests from the browser, calls a method in BusinessEJB, gets the result, and sends the HTTP response.



      Also, ServiceEJB has access to the HttpSession object, where the userId of the user that logged in is stored. BusinessEJBdoes NOT have access to the HttpSession object.



      The application needs to log messages (using sl4j/logback, for example). It could log the message in ServiceEJBor BusinessEJB methods, and when it logs a message, it has to include the userId of the session in the log entry.



      Since BusinessEJB doesn't have the userId, it needs to get it from ServiceEJB. The question is what is the best way to achieve that. What I DON'T want to do is to add a userId field to each method in BusinessEJB as a parameter, as there are many ServiceEJBs and BusinessEJBs in the application (and other beans called by BusinessEJB that also generate log entries), and I don't want to pollute the application with the userId field. Instead, I could have a userId field at the EJB level, but how to populate them? Is there a way to achieve this with annotations? Any suggestions will be welcome.



      @Produces(MediaType.APPLICATION_JSON)
      @Consumes(MediaType.APPLICATION_JSON)
      @Stateless
      public class ServiceEJB

      @Context
      HttpServletRequest httpRequest;

      @Inject
      private BusinessEJB bean;

      private String userId;

      @Path("someurl")
      public Response someMethod1()
      final HttpSession session = httpRequest.getSession();
      // get the userId from the session

      String s = bean.someMethod2();

      // return Response



      @Stateless
      public class BusinessEJB

      private String userId;

      public String someMethod2()
      // .... log an entry with userId
      return "something";











      share|improve this question
















      I have an EJB application that consists of two beans, ServiceEJB (web tier) and BusinessEJB (business tier), where BusinessEJBis injected in ServiceEJB.



      ServiceEJBreceives HTTP requests from the browser, calls a method in BusinessEJB, gets the result, and sends the HTTP response.



      Also, ServiceEJB has access to the HttpSession object, where the userId of the user that logged in is stored. BusinessEJBdoes NOT have access to the HttpSession object.



      The application needs to log messages (using sl4j/logback, for example). It could log the message in ServiceEJBor BusinessEJB methods, and when it logs a message, it has to include the userId of the session in the log entry.



      Since BusinessEJB doesn't have the userId, it needs to get it from ServiceEJB. The question is what is the best way to achieve that. What I DON'T want to do is to add a userId field to each method in BusinessEJB as a parameter, as there are many ServiceEJBs and BusinessEJBs in the application (and other beans called by BusinessEJB that also generate log entries), and I don't want to pollute the application with the userId field. Instead, I could have a userId field at the EJB level, but how to populate them? Is there a way to achieve this with annotations? Any suggestions will be welcome.



      @Produces(MediaType.APPLICATION_JSON)
      @Consumes(MediaType.APPLICATION_JSON)
      @Stateless
      public class ServiceEJB

      @Context
      HttpServletRequest httpRequest;

      @Inject
      private BusinessEJB bean;

      private String userId;

      @Path("someurl")
      public Response someMethod1()
      final HttpSession session = httpRequest.getSession();
      // get the userId from the session

      String s = bean.someMethod2();

      // return Response



      @Stateless
      public class BusinessEJB

      private String userId;

      public String someMethod2()
      // .... log an entry with userId
      return "something";








      java java-ee java-8 ejb cdi






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 28 at 13:52







      ps0604

















      asked Mar 28 at 0:15









      ps0604ps0604

      61613 gold badges55 silver badges150 bronze badges




      61613 gold badges55 silver badges150 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          3















          A few pointers/comments:




          1. If you integrate with application server security, then the user name is available at any component. EJBs can get it by calling getCallerPrincipal() on the injected variant of the EJBContext, here the javax.ejb.SessionContext:



            @Resource
            private SessionContext sessionCtx;


            Servlets can retrieve the principal from the HttpServletRequest.getUserPrincipal(). JAX-RS components (the ServiceEJB) can retrieve it from the javax.ws.rs.core.SecurityContext.getUserPrincipal().



            Is there any reason why you are NOT integrating with the application server security?



          2. If you have a good reason NOT to integrate with application server security, I would propose a variation of the solution from the previous answer. The variation is to set the user data from a filter applied to all resources (either servlet filter or JAX-RS ContainerRequestFilter), so that you do not have to worry about setting it in multiple places.


          3. If you ONLY NEED THE USER ID FOR LOGGING, I'd suggest you take a look at the concept of Mapped Diagnostic Contexts (MDC) in slf4j. With it you can set the user id early at the beginning of the request and make it available to all logging statements thereafter.






          share|improve this answer

























          • Thanks, I ended up using MDC, the simplest solution.

            – ps0604
            Mar 28 at 15:30


















          2















          Create a request scoped CDI bean i.e. UserContext.



          Inject it into both EJBs.



          In ServiceEJB set user's id and in BusinessEJB read it.






          share|improve this answer



























            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%2f55388364%2fpass-value-to-injected-ejb%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3















            A few pointers/comments:




            1. If you integrate with application server security, then the user name is available at any component. EJBs can get it by calling getCallerPrincipal() on the injected variant of the EJBContext, here the javax.ejb.SessionContext:



              @Resource
              private SessionContext sessionCtx;


              Servlets can retrieve the principal from the HttpServletRequest.getUserPrincipal(). JAX-RS components (the ServiceEJB) can retrieve it from the javax.ws.rs.core.SecurityContext.getUserPrincipal().



              Is there any reason why you are NOT integrating with the application server security?



            2. If you have a good reason NOT to integrate with application server security, I would propose a variation of the solution from the previous answer. The variation is to set the user data from a filter applied to all resources (either servlet filter or JAX-RS ContainerRequestFilter), so that you do not have to worry about setting it in multiple places.


            3. If you ONLY NEED THE USER ID FOR LOGGING, I'd suggest you take a look at the concept of Mapped Diagnostic Contexts (MDC) in slf4j. With it you can set the user id early at the beginning of the request and make it available to all logging statements thereafter.






            share|improve this answer

























            • Thanks, I ended up using MDC, the simplest solution.

              – ps0604
              Mar 28 at 15:30















            3















            A few pointers/comments:




            1. If you integrate with application server security, then the user name is available at any component. EJBs can get it by calling getCallerPrincipal() on the injected variant of the EJBContext, here the javax.ejb.SessionContext:



              @Resource
              private SessionContext sessionCtx;


              Servlets can retrieve the principal from the HttpServletRequest.getUserPrincipal(). JAX-RS components (the ServiceEJB) can retrieve it from the javax.ws.rs.core.SecurityContext.getUserPrincipal().



              Is there any reason why you are NOT integrating with the application server security?



            2. If you have a good reason NOT to integrate with application server security, I would propose a variation of the solution from the previous answer. The variation is to set the user data from a filter applied to all resources (either servlet filter or JAX-RS ContainerRequestFilter), so that you do not have to worry about setting it in multiple places.


            3. If you ONLY NEED THE USER ID FOR LOGGING, I'd suggest you take a look at the concept of Mapped Diagnostic Contexts (MDC) in slf4j. With it you can set the user id early at the beginning of the request and make it available to all logging statements thereafter.






            share|improve this answer

























            • Thanks, I ended up using MDC, the simplest solution.

              – ps0604
              Mar 28 at 15:30













            3














            3










            3









            A few pointers/comments:




            1. If you integrate with application server security, then the user name is available at any component. EJBs can get it by calling getCallerPrincipal() on the injected variant of the EJBContext, here the javax.ejb.SessionContext:



              @Resource
              private SessionContext sessionCtx;


              Servlets can retrieve the principal from the HttpServletRequest.getUserPrincipal(). JAX-RS components (the ServiceEJB) can retrieve it from the javax.ws.rs.core.SecurityContext.getUserPrincipal().



              Is there any reason why you are NOT integrating with the application server security?



            2. If you have a good reason NOT to integrate with application server security, I would propose a variation of the solution from the previous answer. The variation is to set the user data from a filter applied to all resources (either servlet filter or JAX-RS ContainerRequestFilter), so that you do not have to worry about setting it in multiple places.


            3. If you ONLY NEED THE USER ID FOR LOGGING, I'd suggest you take a look at the concept of Mapped Diagnostic Contexts (MDC) in slf4j. With it you can set the user id early at the beginning of the request and make it available to all logging statements thereafter.






            share|improve this answer













            A few pointers/comments:




            1. If you integrate with application server security, then the user name is available at any component. EJBs can get it by calling getCallerPrincipal() on the injected variant of the EJBContext, here the javax.ejb.SessionContext:



              @Resource
              private SessionContext sessionCtx;


              Servlets can retrieve the principal from the HttpServletRequest.getUserPrincipal(). JAX-RS components (the ServiceEJB) can retrieve it from the javax.ws.rs.core.SecurityContext.getUserPrincipal().



              Is there any reason why you are NOT integrating with the application server security?



            2. If you have a good reason NOT to integrate with application server security, I would propose a variation of the solution from the previous answer. The variation is to set the user data from a filter applied to all resources (either servlet filter or JAX-RS ContainerRequestFilter), so that you do not have to worry about setting it in multiple places.


            3. If you ONLY NEED THE USER ID FOR LOGGING, I'd suggest you take a look at the concept of Mapped Diagnostic Contexts (MDC) in slf4j. With it you can set the user id early at the beginning of the request and make it available to all logging statements thereafter.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 28 at 14:58









            Nikos ParaskevopoulosNikos Paraskevopoulos

            34.7k9 gold badges73 silver badges80 bronze badges




            34.7k9 gold badges73 silver badges80 bronze badges















            • Thanks, I ended up using MDC, the simplest solution.

              – ps0604
              Mar 28 at 15:30

















            • Thanks, I ended up using MDC, the simplest solution.

              – ps0604
              Mar 28 at 15:30
















            Thanks, I ended up using MDC, the simplest solution.

            – ps0604
            Mar 28 at 15:30





            Thanks, I ended up using MDC, the simplest solution.

            – ps0604
            Mar 28 at 15:30













            2















            Create a request scoped CDI bean i.e. UserContext.



            Inject it into both EJBs.



            In ServiceEJB set user's id and in BusinessEJB read it.






            share|improve this answer





























              2















              Create a request scoped CDI bean i.e. UserContext.



              Inject it into both EJBs.



              In ServiceEJB set user's id and in BusinessEJB read it.






              share|improve this answer



























                2














                2










                2









                Create a request scoped CDI bean i.e. UserContext.



                Inject it into both EJBs.



                In ServiceEJB set user's id and in BusinessEJB read it.






                share|improve this answer













                Create a request scoped CDI bean i.e. UserContext.



                Inject it into both EJBs.



                In ServiceEJB set user's id and in BusinessEJB read it.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 28 at 14:03









                srnjaksrnjak

                6706 silver badges17 bronze badges




                6706 silver badges17 bronze badges






























                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55388364%2fpass-value-to-injected-ejb%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript