Managed session bean in servlet filter

Hi,
Is there a way to get hold of a managed bean with session scope in a servlet filter? The code below throws an error due to the fact that the faces context is null.
FacesContext facesContext = FacesContext.getCurrentInstance();
System.out.println("facesContext: " + facesContext); // shows that facesContext is null
ApplicationFactory appFactory = ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
Application app = appFactory.getApplication();
Object obj = app.createValueBinding("user").getValue(facesContext); //throws the error due to the null parameter
Object obj2 = app.createValueBinding("user"); //results in a valid ValueBindingHere is the faces-config snippet for the managed bean:
<managed-bean>
    <managed-bean-name>user</managed-bean-name>
    <managed-bean-class>biz.libereco.skemo.info.asl.beans.User</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>For the record, I am using JSF 1.0 Final.
Thank you,
Marcel

wynton_0 wrote:
Yes, there is a way to get hold of a managed bean with session scope in a servlet filter.
See here:
[http://wiki.apache.org/myfaces/AccessFacesContextFromServlet]
and here:
[how to access faces context and backing beans in a servlet filter|http://www.thoughtsabout.net/blog/archives/000033.html]
This makes no utter sense. A JSF session scoped managed bean is under the hood just put as a HttpSession attribute with the managed bean name as key. Guess what, you can just access the HttpSession in Filter by ((HttpServletRequest) request).getSession() and then just call getAttribute() on it. If it isn't there yet, then just do a setAttribute() with a new instance.
After I get User bean in my Servlet filter, I populate value to this bean, for example:
user.setLanguage(request.getParameter("locale"));
The User bean is in session scope. The User bean's language attribute suppose to be same in the whole session scope, but later on, I got null. My question is:
how to keep this value in session scope?The the session was apparently invalidated/renewed or you manually removed the bean or replaced it by null.
In the future, please don't resurrect old topics, just start a new topic for each independent problem/question.

Similar Messages

  • Accessing Managed Session Bean in Servlet Filter

    I wrote a Servlet Filter to handle user authentication. Now I'm trying to access my Managed Session Bean in the filter in order to save the current user. Unfortunately the Session Bean is created after the Filter executes for the first time.
    I'm trying to access the Session Bean in this way:
    (SessionBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sessionBean");
    In this case getExternalContext() is equals null.
    Is there any way to create the Session bean before the filter executes or any other ideas how to handle this?
    I already searched around the internet but couldnt figure out something.
    Thanks guys,
    Paul

    Ok, fixed it like this. Works perfect. JSF finds and uses the handmade Session Bean as well.
    if(request.getSession().getAttribute(BeanNames.SESSION_SCOPE_BEAN) == null) {
         SessionBean sessionBean = new SessionBean();
         request.getSession().setAttribute(BeanNames.SESSION_SCOPE_BEAN, sessionBean);
    }Thanks,
    Paul

  • Access of JSF Beans from Servlet Filter

    Is there any way how can I access session JSF beans from servlet filter?
    I need to check certain value of JSF bean stored in session scope in my filter.
    Thanks
    ferdo

    Frank,
    I am not sure about phase listener, this is the whole situation:
    as I am not using Container Managed Security with my JSF, after I do sucessfull login into application, I need to store some information into the session scope (user etc) and in the servlet filter I need to find out if the user is connected.
    I was trying to put such info into Servlet Session directly in my bean via External Context and reading the info in Filter.
    This is working fine when my application is running locally (jdev oc4j) but once deployed into Application server, when user login first time, user information is somehow removed from the session, and cannot figure out why.
    So I was thinking to try another approach, to find out from servlet filter if JSF bean value is set or not.
    Any other suggestions? Do not want to swicth to Container Manages Security now.
    ferdo
    null

  • Calling Stateless Session bean from Servlet

    Dear Friends,
    A help will be Appreciated...
    I created a EJB (Stateless Session Bean) using WebSphere Application Developer with its Business logic in Main bean. Its working perfectly fine using UTC (Standalone Test Client). But when i use a servlet to communicate with this EJB, its giving me error as follows:
    Error Stack:
    java.lang.NoClassDefFoundError: package name/DemoHome
    at java.lang.Class.newInstance0(Native Method)
    at java.lang.Class.newInstance(Class.java:254)
    at java.beans.Beans.instantiate(Beans.java:213)
    at java.beans.Beans.instantiate(Beans.java:57)
    at com.ibm.servlet.engine.webapp.WebAppServletManager.loadServlet(WebAppServletManager.java:148)
    at com.ibm.servlet.engine.webapp.WebAppServletManager.getServletReference(WebAppServletManager.java:287)
    at com.ibm.servlet.engine.webapp.WebApp.getServletReference(WebApp.java:354)
    at com.ibm.servlet.engine.webapp.WebAppRequestDispatcherInfo.calculateInfo(WebAppRequestDispatcherInfo.java:167)
    at com.ibm.servlet.engine.webapp.WebAppRequestDispatcherInfo.<init>(WebAppRequestDispatcherInfo.java:51)
    at com.ibm.servlet.engine.webapp.WebApp.getRequestDispatcher(WebApp.java:1145)
    at com.ibm.servlet.engine.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:179)
    at com.ibm.servlet.engine.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:67)
    at com.ibm.servlet.engine.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:122)
    at com.ibm.servlet.engine.oselistener.OSEListenerDispatcher.service(OSEListener.java:315)
    at com.ibm.servlet.engine.http11.HttpConnection.handleRequest(HttpConnection.java:60)
    at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:323)
    at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:252)
    at com.ibm.ws.util.CachedThread.run(ThreadPool.java:122)
    For more Info let me provide the snipets of how i used the Sevlet:
    Client.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import packagename.*; //package name of imported ear file which is in
    //classpath
    public class Client extends HttpServlet {
    public void doGet(
    javax.servlet.http.HttpServletRequest request,
    javax.servlet.http.HttpServletResponse response)
    throws javax.servlet.ServletException, java.io.IOException {
    PrintWriter out=response.getWriter();
    Properties p = new Properties();
    p.put(javax.naming.Context.PROVIDER_URL, "iiop:///");
    p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
    try {
    InitialContext initial = new InitialContext(p);
    Object objref = initial.lookup("JDemo");
    DemoHome home = (DemoHome)PortableRemoteObject.narrow(objref,DemoHome.class);
    Demo demo = home.create();
    int r=demo.testBean(4);
    out.println("EJB RESULT= "+r);
    } catch (Exception ex) {
    System.err.println("Caught an unexpected exception!");
    ex.printStackTrace();
    Kindly provide ur solution to this problem. Urgent solution will be helpful as its a part of our present project.
    Thanking you for ur esteemed help.
    regards,
    Arun.

    Perhaps you webserver can't see your package jar file.
    Try putting it in WEB-INF\lib directory of your app and restart your server.

  • How to init the managed session bean?

    Hi, suppose we have a session bean like this:
    <managed-bean>
        <managed-bean-name>A</managed-bean-name>
                <managed-bean-class>
         a.A
                </managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>I want to clear the states of A, so i need to reinitialize it,how to do that?

    Y_Not, i find there is some problem with the line:
    createValueBinding( "#{yourSessionBeanName}").setValue(FacesContext.getCurrentInstance(),null);later,when i again what to use my session bean, i will got an java.lang.NullPointerException, so i guess when there is a ValueBinding trying to get the bean,if the bean is null, jsf impl will not initialize it automatically, is that true?
    But i think the class of the session bean has been specified, so jsf should be capable of initializing it whenever it is null and someone try to get it.I am using myfaces, i don't know if this not happens with sun implemenation.
    so maybe i have to use the following line instead of the one above:
    createValueBinding( "#{yourSessionBeanName}").setValue(FacesContext.getCurrentInstance(),new YourSesssionBeanName());Obviously,this is not convenient.
    Best Regards:)

  • How do you use one managed session bean from another?

    Hello -
    I am a complete newbie to JSF coming from Struts 1. My question is how do you use one managed bean from the method of another one? I think this would be a common senario. For example I put a bean in session scope when a user logs in and in a different method within a different bean I want to get some of this user's information. What is the correct way to retireve one bean from a method in another with session scope?
    Also what would the code look like to retieve another bean from the method of a managed bean where the bean you want to retrieve has application scope?
    Thank you in advance.

    Sinplicity wrote:
    Could you be a bit more specific? If a bean is configured in the faces config file then all of it's properties are managed, correct?Not necessarily.
    What would the code look like to retireve the bean?You don't retrieve it, it has been injected.
    Can I retrieve the whole bean or just a property of the bean. I would be really interested in seeing how this is done in code? And would really love a bit more information on what it means to be a managed property?Time to consult a JSF tutorial.

  • How do I lookup an EJB 3.0 Session bean from servlet or JSP?

    Does anyone knows how can I invoke an EJB from a servlet or JSP ?
    I deployed a simple EJB on a Oracle Application Server 10g release 10.1.3 and I'm working with JDeveloper 10.1.3. I deployed the files via JDeveloper, and I didn´t specify any orion-ejb-jar.xml or ejb-jar.xml file
    After deployment, the orion-ejb-jar.xml look like this in the server:
    <?xml version="1.0" encoding="utf-8"?>
    <orion-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/orion-ejb-jar-10_0.xsd" deployment-version="10.1.3.0.0" deployment-time="10b49516c8f" schema-major-version="10" schema-minor-version="0" >
    <enterprise-beans>
    <session-deployment name="HolaMundoEJB" location="HolaMundoEJB" local-location="HolaMundoEJB_HolaMundoEJBLocal" local-wrapper-name="HolaMundoEJBLocal_StatelessSessionBeanWrapper6" remote-wrapper-name="HolaMundoEJB_StatelessSessionBeanWrapper7" persistence-filename="HolaMundoEJB.home_default_group_1">
    </session-deployment>
    </enterprise-beans>
    <assembly-descriptor>
    <default-method-access>
    <security-role-mapping name="<default-ejb-caller-role>" impliesAll="true" />
    </default-method-access>
    </assembly-descriptor>
    </orion-ejb-jar>
    I'm trying to invoke the ejb in a servlet by doing the following:
    public void doGet(HttpServletRequest request, ....
    Context context = new InitialContext();
    HolaMundoEJB helloWorld =
    (HolaMundoEJB)context.lookup("java:com/env/ejb/HolaMundoEJB");
    String respuesta = helloWorld.sayHello("David");
    When i invoke the servlet I catch a NamingException whose message says something
    like this ....java:com/env/ejb/HolaMundoEJB not found in webLlamaEJB
    I tried different paths for the lookup but nothing....
    Can anyone help me with this topic? Thank you.

    Please try the following code:
    HelloEJBBean.java:
    @Stateless(name="Hello")
    @Remote(value={Hello.class})
    public class HelloEJBBean implements Hello {  ... }
    hello.jsp:
    Context ctx = new InitialContext();
    Hello h = (Hello)ctx.lookup("ejb/Hello");
    web.xml:
    <ejb-ref>
    <ejb-ref-name>ejb/Hello</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <remote>fi.kronodoc.test.model.Hello</remote>
    </ejb-ref>
    i think you should also define jndi mappings for the references in orion-ejb-jar.xml and orion-web.xml but for some reason it seems to be working also without these.

  • Getting error after when trying to print managed session bean property.

    Hi All,
    I am reading a file from my local machine. After reading a file , i am storing file details in the property of the same bean.
    After that i am trying to preint contents of that file in one jsp by accessing that stored managed bean property.
    But I am getting following error:
    Nov 15, 2009 2:33:41 PM com.sun.faces.lifecycle.LifecycleImpl phase
    WARNING: executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@138c63) threw exception
    javax.faces.FacesException
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:135)
         at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
         at java.lang.Thread.run(Unknown Source)
    Caused by: ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
         at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:319)
         at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:288)
         at org.apache.catalina.connector.Response.flushBuffer(Response.java:548)
         at org.apache.catalina.connector.ResponseFacade.flushBuffer(ResponseFacade.java:279)
         at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:201)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106)
         ... 15 more
    Caused by: java.net.SocketException: Connection reset by peer: socket write error
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(Unknown Source)
         at java.net.SocketOutputStream.write(Unknown Source)
         at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:740)
         at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:434)
         at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:299)
         at org.apache.coyote.http11.Http11Processor.action(Http11Processor.java:973)
         at org.apache.coyote.Response.action(Response.java:183)
         at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:314)
         ... 20 more
    Nov 15, 2009 2:33:41 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    java.net.SocketException: Connection reset by peer: socket write error
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(Unknown Source)
         at java.net.SocketOutputStream.write(Unknown Source)
         at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:740)
         at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:434)
         at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:299)
         at org.apache.coyote.http11.Http11Processor.action(Http11Processor.java:973)
         at org.apache.coyote.Response.action(Response.java:183)
         at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:314)
         at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:288)
         at org.apache.catalina.connector.Response.flushBuffer(Response.java:548)
         at org.apache.catalina.connector.ResponseFacade.flushBuffer(ResponseFacade.java:279)
         at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:201)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106)
         at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
         at java.lang.Thread.run(Unknown Source)There is no specific reason mentioned for this error. Anyone has faced this problem before?
    Whats wrong here?

    Hi gimbal2,
    I haven't deployed the project yet. I am still in development phase. I am using eclipse. So i am using inbuilt browser from eclipse only.
    I saw this post on the same forum:
    http://forums.sun.com/thread.jspa?threadID=5297862
    This person had the same problem. But his question is not answered yet.
    People here are saying:
    *1)page is getting submitted more than once. Either because the user is clicking on the commandbuttons/links multiple times or through some other event.*
    ->I am not using any javascript. But problem here is whenever i try to load file from my local machine, in first attempt it wont proceed. I need to load file twice or thrice. Is it some problem?
    But one thing to note here is that i am not getting exception after loading the file. I am getting exception after reading the file in managed bean and returning from it with some status.
    *2)This exception can be caused by the browser closing its end of the socket for any number of reasons (user presses stop loading button, clicks another link, closes the browser window, etc.):*
    ->I am not pressing any button or doing any activity once i load the file.
    *3)Sounds like it should be caught and ignored since these are normal user actions. I was just concerned it might be causing some kind of impact that we don't know about.*
    ->I can't ignore it because, my next JSP is not getting loaded after i return from the read file bean.
    Hope People here can help me solve this problem. I am not able to proceed :(

  • How to call a  servlet in a Session Bean

    Hi All
    I have one servlet program.And i have One Sessionbean.
    I want to call the servlet in the session bean.
    I am using Runtime method in java to call the servlet by giving it's full
    path as it's argument.
    But it is not working fine.I don't know what is the Problem.
    Bye
    Satyam

    Hi,
    I don't know why you want to do that? You should be doing the other way round i.e. call your session bean from servlet.
    I must say that servlets are presentation tier components and session beans are middleware components related to workflow.
    HTH
    VJ

  • Stateless Session Bean lookup truble on standalone OC4J (9.0.3)

    Hi all,
    I've folowing truble:
    I deploy my app, start browser and get an Excwption
    javax.naming.NamingException: Error instantiating web-app JNDI-context: No location specified and no suitable instance found for the ejb-ref 'ejb/ActivationSessionHome', an EJB with matching home and remote name was found, but it was an Entity, not a Session.
    If I deploy my Session Bean as Entity the Exception ended:
    ..., but it was a Session, not an Entity.
    Please help me understand and fix this %-(
    Thanks.

    Hi Vladimir,
    I understand that you are trying to access a session bean from a servlet where both the session bean and servlet are part of the same J2EE application that you have deployed to (stand-alone) OC4J. If this is correct, then have you seen the following tutorial (which does exactly the same thing):
    http://kb.atlassian.com/content/tutorials/jollem/orion-primer/
    Hope this helps you.
    Good Luck,
    Avi.

  • Transaction Mgmt. Code In Servlet Filter

    Hi,
    It it possible to write Transaction management code in the Servlet filter. I am confused on this isssue, as "Designing Enterprise Applications with the J2EETM Platform, Second Edition" under section "8.5 Web Tier Transaction Guidelines" says that you can not use transaction management code in the Servlet Filters. But if adventure builder sample has code which uses transaction management code inside the servlet filter named as "Transaction Filter".
    Regards,
    Manish

    Hi,
    The paragraph you quote just implies that it is not guaranteed to work under the 'standard' J2EE servers like your everyday appserver. This is because the specs just don't require it. But different products may have different ideas;-)
    Best,
    Guy
    http://www.atomikos.com

  • Session bean with 2 entity bean

    i have a phonebook manager (session bean) taht controls the category of contacts such as group a , group b, group c and group d. where group a b c and d are all entity beans.
    may i know how to control a session bean so that it can diferent which entity beans to invoke ?

    Group might be a table in a database,
    GroupEJB referes to Entity Bean.
    with the following fields. Group Id , Group disciption. where group ID is primary Key.
    Use a session bean and create your group A B C D.( EJB create method).
    Simple i guess.
    Enjoy
    Zoha.

  • Need urgent help: how to avoid concurrent calls on statefull session beans

    Hi,
    I need a little advice in designing a EJB session facade using JSPs, servlets, session and
    entity beans.
    My current design is:
    - JSP pages: here are only getMethods for the session bean used. All set-methods are handled by a
    - servlet: I have got one servlet handling several JSP pages. The servlet basically takes the
    form fields and stores them in the session bean and than dispatches to the next JSP-page
    - stateful session bean: here is, where all the business logic is conducted. There is one session
    bean per servlet using several
    - CMP entity beans: to talk to the database (Oracle 8i)
    The application server is JBoss 3.0.3.
    My problem is, if a user clicks on a submit button of a JSP page more than once before the next
    page builds up, I may get a "javax.ejb.EJBException: Application Error: no concurrent calls on
    stateful beans" error. I already synchronized (by the "session") the code in the servlet, but
    it happens in the JSP pages as well.
    I know, that Weblogic is able to handle concurrent calls, by JBoss isn't and it's clearly stated
    in the spec, that a user should avoid to have concurrent calls to a stateful bean.
    The big question is now: How can I avoid this? How can I prohibit the user to submit a form several
    times or to ignore anything, which arrives after the first submit?
    Thanks for any help,
    Thorsten.

    Synchronizing on the session is probably your best bet.
    You'll need to do all the data access and manipulation in the servlet. Cache any data you need using request.setAttribute() and then not access the EJB on the JSP page.
    If performance is an issue, you may also want to use create a user transaction to wrap all the EJB access in, otherwise each EJB call from the servlet is a new transaction. Just make sure you use a finally block to properly commit/rollback the transaction before you redirect to the JSP.
    UserTransaction utx    = null;
    synchronized (request.getSession())
      try {
        Context ctx = new InitialContext();
        utx = (UserTransaction) ctx.lookup("javax/transaction/UserTransaction");
        utx.begin();
        // ... Create session bean ...
        request.setAttribute("mydata", sessionBean.getMyData());
        try {
          utx.commit();
        catch (Exception ex) {
          log.warn("Transaction Rolled Back (" + ex.getClass().getName() + "): "
            + ex.getMessage(), ex);
        utx = null;
      } // try
      finally {
        if(utx != null)
          try {
            utx.rollback();
          catch (Exception e) {
            log.warn(e.getMessage(), e);
          } // catch
        } // if
      } // finally
    } // syncrhonized(session)

  • EJB 3.0 Stateful session bean shared between Servlet's

    Hello
    I have a bit of a noob question regarding Stateful sessions beans.
    I am wanting to know if there is a way that I can share an instance of a session bean between multiple HttpServlet instances?
    I am sending XML messages from a mobile J2ME application, there will be several http POST's made from the mobile client to the server. I would like these multiple POST's to be passed from the handling servlet instance to the same uniquely identified single stateful session bean instance (i can then @Remove the stateful bean when I have finished my several requests).
    I would greatly appreciate any tips anyone could give me.

    If not, your only option is to maintain the
    association yourself by creating a unique id for
    each
    conversation and storing that id along with the SFSB
    reference in the ServletContext. Then you'll
    need to pass the id in along with each invocation to
    retrieve the appropriate SFSB reference.Thanks for your reply.
    Will I always be presented with the same ServletContext instance? Even if the time between requests might be many minutes? Where can I learn more about how to use the ServletContext?
    Thanks!

  • Context.lookup in a Servlet always returns the same Stateful Session Bean

    Hi,
    I am working on an application in which a Servlet should obtain one StateFul Session Bean per client. I read in EJB 3.0 in Action that to do so I should use a jndi lookup and save the result of the lookup in an HttpSession. This works fine for me when I have a single client.
    My issue is that when I have several clients, context.lookup returns the same SFSB for each client. This means that I end up having a single SFSB for the whole application. I've been browsing the web for a while now trying to find a solution but haven't had any luck yet.
    The code I use to obtain and save the SFSB is the following:
    HttpSession session = request.getSession(true);
    DFMServiceRemote service = (DFMServiceRemote) session.getAttribute("DFMService");
    if (null == service)
         service = (DFMServiceRemote) new InitialContext().lookup("DFMService");
         session.setAttribute("DFMService", service);
    }Using different browser, I end up with different HttpSession but a single SFSB. The only workaround I found is to create the context with environment variables or properties. It then returns different SFSBs for different HttpSession. The workaround code is as below:
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.evermind.server.rmi.RMIInitialContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, "oc4jadmin");
    env.put(Context.SECURITY_CREDENTIALS, "welcome");
    env.put(Context.PROVIDER_URL, "ormi://localhost:23791/DriverFatigue");
    service = (DFMServiceRemote) new InitialContext(env).lookup("DFMService");My question is the following. How can I get a different instance of an SFSB every time I execute context.lookup without specifying properties.
    Thanks in advance for any help,
    Matthieu Siggen

    I just did something similar in another project using JBoss instead of oc4j and didn't have any problem. I expect I missed a configuration file in oc4j or there is a conflict somewhere.

Maybe you are looking for