Sharing an object between Servlets

I am using a Connection object to query a database from a few different servlets. Is there a way I can pass it between the Servlets, so that I don't have to keep re-opening the connection for each Servlet?

I may have mis-understood your question. Do you want to keep the "same" connection open between servlets, e.g. pass around ResultSet objects? If so, and I've not tried this with connection pooling, it should still work, you simply pass the connectin reference object to the other servlet and don't close it. Though most will probably call this bad development practice (e.g. leaving connections open while jumping around Servlets). If so, I like to here the "best practice" approach.
bRi

Similar Messages

  • Sharing an object between other objects?

    I have two classes, say DisplayPanel and ControlPanel. Both of these classes need to have access to a single instance of an object of type Data, say theData. I want to be able to set theData to a new object at any time, for example, theData = new KindOfData().
    If I store a reference to theData in both objects, when I set theData to a new object in one class, the other will still reference the old object. Is there a way to share an object between two classes as I described?
    I could create a superclass for DisplayPanel and ControlPanel that contains an instance of Data, however I may need to access this object in other classes and do not want to have the inflexibility of having to extend a possibly unrelated class just to access a single data member.
    Is there any easy way to go about this? Thanks for your help.

    Create a listener interface. Make each class implement that interface. When you create each class, register it as a listener to theData. Keep track of all listeners in a List such as an ArrayList. When you want to change theData, iterate through the List and call the interface's method to update theData in each class:
    public interface SomeListener
       void updateData(KindOfData theData);
    public class DisplayPanel implements SomeListener
      private KindOfData theData;
      public void updateData(KindOfData newData)
         theData = newData;
    public class SomeOtherClass
       private List listenerList = new ArrayList();
       public void addDataListener(SomeListener listener)
            listenerList.add(listener);
       public void fireDataChange(KindOfData newData)
           for (Iterator listenerIter = listenerList.iterator();
                  listenerIter.hasNext();
               ((DataListener)listenerIter.next()).updateData(newData);
    }Look at how EventListeners are added and fired in Swing classes.

  • (UIX XML) Sharing Connection objects between BC4J and custom java.

    If I have a UIX XML page that contains some BC4J application modules, then in the event handler I call [public static EventResult handleMyEventEvent (BajaContext context, Page page, PageEvent event..) ], which in turn calls some java classes I have written that take a java.sql.Connection object and access the database doing some updates/inserts with this Connection object (via JDBC)....HOW CAN I USE THE SAME TRANSACTION AS WAS USED IN THE BC4J APPLICATION MODULE...i.e. CAN I SHARE THE CONNECTION OBJECT BETWEEN BC4J AND MY OWN JAVA CLASSES THAT USE JDBC?
    What are the best ways to share such a transaction?
    Thanks,
    Paul.

    Would it be easier to use a custom method on the bc4j Application module?
    Take this scenario...
    1. User opens UIX XML web page which opens a bc4j App Module..it has a VO based on all employees.
    2. User presses the add button and a new employee is created (using the bc4j App Module).
    (Notice: no commit yet!)
    3. User presses the submit button...fires event REVIEW_SALARY.
    4. This event is 'handled' in the event section of the UML XML...it calls:-
    public static EventResult handleREVIEW_SALARYEvent (BajaContext context, Page page, PageEvent event)...
    5. I now want to call a java class I wrote that computes an employees new salary and updates the employee record with this new salary. This update will fail unless it is part of the same transaction as the one used by the bc4j App Module (that inserted the new employee).
    How best to proceed from here?
    How about having a method on the bc4j App Mod's VO called 'reviewSalary'? Calling this would use the same transaction? I could then call my java class from within the VO's method? However do I still have the same problem in that my java class expects to be passed the connection object?
    The approach you suggested previously seems a touch dangerous....in that these are not 'publically exposed'...and a new release of JDev may break my code.
    Thanks,
    Paul.

  • Urgent: problem with sharing HttpSession  object between Jsp and servlets.

    Hi,
              We are using weblogic 6.0 sp2.
              I m setting a particular object in session in a servlet using
              session.setAttribute() but when i try to retrieve that object using
              session.getAttribute() in a jsp page the value of that object is null. Is
              there any way to configure HttpSession in weblogic so that jsps and servlet
              can share the same session? Or any workaround for this problem.
              Any help in this regard is appreciated.
              Thanks
              -Shree
              

    Just a guess, but it sounds like you have cookies turned off and are not
              using encodeURL. Try enabling cookies and see if that solves the problem.
              Also, it is generally good practice to use encodeURL to protect yourself
              from users who disable session cookies.
              Here's how we use encodeURL in our Servlets:
              gotoPage("/jsp/someJSP.jsp");
              private void gotoPage( String address,
              HttpServletRequest request,
              HttpServletResponse response )
              throws ServletException, IOException
              RequestDispatcher dispatcher =
              etServletContext().getRequestDispatcher( response.encodeURL( address ));
              dispatcher.forward( request, response );
              "Shree Unde" <[email protected]> wrote in message
              news:[email protected]..
              > Hi,
              > We are using weblogic 6.0 sp2.
              > I m setting a particular object in session in a servlet using
              > session.setAttribute() but when i try to retrieve that object using
              > session.getAttribute() in a jsp page the value of that object is null. Is
              > there any way to configure HttpSession in weblogic so that jsps and
              servlet
              > can share the same session? Or any workaround for this problem.
              > Any help in this regard is appreciated.
              > Thanks
              > -Shree
              >
              >
              

  • Sharing socket object between threads - Is any sync required?

    For example, a thread receives (listens) datagram packets at incoming socket and forwards them downstream through another datagram socket. Another thread listens packets at this second socket and forwards the data via the first socket. It is possible that two threads invoke methods of the same socket (one is receiveng while another is sending). This situation is not described in the DatagramSocket manual. I beleive there is underlying synchronization at the OS kernel level. Can I relay on it? Thanks.

    I expected some critics for using old plain sockets instead of nio :)You should use NIO if you have hundreds of connections. If you have a small number of connections and want a simple implementation use blocking IO as you have.
    If you can have different
    threads reading or writing at once eg two readingor
    two writing then you need to use synchronisation.Shouldn't this be stated by the API designers somewhere?It is probibly covered in a tutorial or example somewhere.
    You have a different input and output stream. There is a lock on each. This is your best hint.
    Theoretically, nothing prohibits sending UDP packets in race conditions.
    In fact, this is what my program
    does - it respondes to different clients using one
    (server) datagram socket. The responses are produced
    by multiple threads. I suppose that java does not
    involve any state variables; thus, beleive that the
    system can accomplish the synchronisation unnecesary
    at the application level.That depends on how you build and send your messages. If each part of the message can be sent in one hit and the order does not matter you are fine.
    If you have a single object shared between threads, then all members are shared, not just static variables.

  • How to pass objects between servlet services

    I wanted to pass an object from one service to another service and that object must be visible only for these two services. I don't want to use session.setAttribute or session.getAttribute to do this. When I use request.setAttribute and request.getAttribute methods not helping me to do this. Is there a way to do this?
    Between, how these request.setAttribute and request.getAttribute methods useful?
    regds
    -raju

    Actually, I set attribute in one of the service
    methods. Within that service method a form will be
    there. After pressing submit button in that form, the
    other service will be called. Does it mean that both
    the services are not in the same request scope, even
    if they are in the same servlet?They are on different request scopes. Each time the user clicks a link, they make a request to the server. The server processes the request creates a response and send that response back to the client. Once the response it sent (and finished being sent) the request is done with, and anything is request scope goes out of scope. When the user clicks the submit button, a NEW request (and request scope) is made to handle that ...
    Your best bet is to use a session here. It is the easiest way to maintain state between requests. That is what the session is designed for.

  • Send objects between servlets

    I have two servlets. One of them knows about an object called User. What I want to do is send this object to the other servlet in some way, since I need it to also know about User. Yet none of the servlets have an instance of the other servlet, so they don't know about each other.
    Is there a way to send an object from one servlet to another?

    Yes there is..
    Put it in session in the first servlet
    session.setAttribute("attributeName",Object);
    in the second servlet get it by
    session.getAttribute("attributeName")
    Be careful to cast it in the proper object, because the session object contains Objects

  • Passing objects between Servlets and JSP

    Hi,
    I have passed a ResultSet from a Servlet to JSP using RequestDispatcher forward(). I can access the ResultSet in the JSP page. How can I now pass this ResultSet into another JSP page once the form has been submitted?
    Thanks in advance.

    You should never passing expensive resources like ResultSet around like that. This indicate an open DB connection somewhere while it should already be closed at this stage.
    Read on about the DAO pattern and make use of servlets and beans.

  • Sharing an object/class bewteen servlets and applications

    Hi there,
    I wish to know how to share a class/object between all
    types of other classes, be they applications or servlets, but I encounter the following problem.
    Basically, if I instantiate the common class using, say a servlet, then when I try to gain a handle on the instance of that class from an application, the application creates a new(or it's own) instance. Similarly, if I instantiate first within an application.
    How do I prevent this from happening?
    The actual class files for both the application and servlets are all the same.
    Appreciate the help,
    Fintan.

    I am actually implementing the singleton pattern in
    this common class.ok, that clarifies the issue a bit...
    The RMI route seems to me to be a bit too much work > as a solution to a very simple concept.actually, it's really not a simple concept. What you really want isn't just an application singleton, where there is one instance in the application/servlet JVM. What you really want is more along the lines of a universal singleton, where there is only one instance for ALL applications/servlets...
    Interestingly, if I run two java apps side by side in
    two DOS windows that each call a getInstance
    method in common singleton, both apps create their
    own instance.
    How come? Separate instances of VM?Yes, this is exactly correct. The same is true of C++ Singletons; if you start a second application it will create another instance of the Singleton because one does not yet exist in the application.
    How do I get aroun this one?Like I said, think of it as a universal singleton. Consider Verisign a universal singleton--everyone comes to them for certificates. How does this run? Well, truthfully, Verisign operates as a service, right? So you need some way of setting up a service that really holds onto the object and brokers (aha, 5 dollar word!) who has access to it, who can modify it, and who can read from it. This leads you to a few options... RMI, CORBA, or writing your own object server.
    Networking is really easy in Java, so here's another option... You can set up a server that listens for messages on a specific socket/port with whatever protocol you specify to get/set values. Have the server run on only one specific machine. Then you can have all the servlets and applications come to the machine to get the information.
    Gee, this sounds like a back-end database. =)
    If all this is too complex, maybe you need to rethink the design... do you really need to have the exact same object shared between all application/servlet instances? Or is it acceptable to just make sure they all contain the same data?
    If what you really want is a real-time data update scheme, then you probably want something like a subscribe-publish architecture where the one server publishes the origainal data. Then when a client updates the server, the server posts an update message to all the clients, who then in turn update their internal data.
    Anyway, I'm just throwing out some ideas. I'm sure you can come up with some better ones of your own since you know what your requirements are. =)
    Once again appreciate the help!I hope it actually was. =)
    --David

  • How to share objects between two ADF Faces servlet sessions

    I gather the application scope is one way to go for sharing data between sessions in an ADF application. Are there other more generic methods of sharing data between servlet sessions?
    For example, let's say we have a JDev 101.3 ADFBC/JSF app. (or JDev 11g for that matter). In this app we also register a servlet in web.xml. So two people log into this application and access this defined servlet, creating two instances of that servlet...I guess. Is there a way for those two instances/sessions to talk to each other? Pass data back and forth? Should I read about JMS? Or does application scope sound better? I guess a direct communication would be more tidy, than putting data on an application bulletin board, lilke application scope.
    Any thoughts?

    Hi,
    Only one instance of each servlet defined in web.xml gets created, not one per user. You're right about the sessions though, one per user is created. You're right on the other parts as well I think you could use application scope to do something like that, or the data base for that matter, depending on the use case.
    Regards,
    ~ Simon

  • What's the best way to share JE environments between servlets?

    Hi, I'm happily serving requests for the same webapp (so single servlet) which uses multiple JE environments. In my case I have an environment for each db, one of these environments is a login details only db. Things work great, three questions though:
    1. Right now I'm keeping environment/entity store references in global vars (everything below entity store, views etc. is created and discarded for each request), is there a better way?
    2. When I want to add a new app (so additional servlet) - how can I make sure the login environment is shared across servlets, to take advantage of shared cache etc?
    3. As indexes are thread safe, is it considered best practice to store index refs. in global vars. and have each incoming thread (in a servlet) share these vars. or should each request build the object refs. it uses and discard accordingly?
    Hoping the above makes sense.
    PhilQ.

    Yes, EntityIndex objects are also thread-safe. Really only EntityCursor objects are not.
    The entity objects themselves are not owned by JE. You will have problems if you have multiple threads changing them concurrently (if one thread is changing an entity object's properties and another thread is storing it, for example). However, it is up to you if you want to share entity objects between threads; there is nothing wrong with that, since there is no interaction with JE. But your app will need to enforce thread safety, perhaps by using them only in a read-only fashion, for example.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to exchange information(parameters) between servlets & jsps

    with an examle if possible.

    Hi
    Exchanging parameters/objects between JSP and Servlets is done by creating an Object and placing it in the ServletContext , User Session or the Request depending on whether the Object requires Application Wide scope, Session Scope or Request Scope respectively.
    If the object is created in the Servlet then it can shared by placing it in either Context, Session or Request through the setAttribute method and similarly retrieved through the getAttribute method.
    For JSP use the <jsp:useBean> tag to retrieve/create the Object (bean).
    For eaxmples see the following Links:
    http://java.sun.com/docs/books/tutorial/servlets/communication/attributes.html
    http://developer.java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro11
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems
    http://www.sun.com/developers/support

  • Sharing view objects across application modules

    Our application uses multiple application modules because of the complex functional requirements. We have come across sharing view objects among application modules. I want to understand the best practice, sharing view object instances across application modules. These view objects can be based on Entity Objects also.
    Please let me know if there any suggestions.
    Thanks,
    Satya

    Hi Satya,
    You won't be able to share view objects between application modules, but what you can do is to share the bind variables between application modules, if each of your module contains the 'common' view object.
    A solution for sharing data between application modules is provided on this blog: http://andrejusb.blogspot.co.uk/2012/05/solution-for-sharing-global-user-data.html
    You can use this approach to share bind variables between AM's and re-query the same data.
    Hope this helps,
    Florin Marcus
    www.redsamuraiconsulting.com

  • Sharing a VLAN between FWSM and ACE (Routed Mode)

    Anybody in here with experience on sharing a Vlan between an ACE and a FWSM module?
    I have a transfer network between the ACE and the FWSM in the same chassis. FWSM gets several vlans and ACE gets some Vlans.
    I wanted to configure it like this.
    firewall vlan group 10 <FWSM only vlans>
    firewall vlan group 20 <shared FWSM and ACE vlan>
    or
    svclc vlan group 20 <shared FWSM and ACE vlan>
    svclc vlan group 30 <ACE only vlans>
    The design hides the client side network and the server side network for the ACE behind the FWSM module.
    Layout:
    |-- Clients <--> MSFC <--> FWSM <--> ACE <--> Server --|
    So allocation on the 65xx would be like this.
    firewall module n vlan-group 10,20
    svclc module n vlan-group 20,30
    Any obvious issues with this design if you share the vlan(s) referred in group 20 with both modules?
    FWSM and ACE will be in routed mode.
    Thanks for reading...
    Roble

    Never mind...
    Just found the perfect answer for this in a another posting from Syed.
    http://forum.cisco.com/eforum/servlet/NetProf?page=netprof&forum=Data%20Center&topic=SNA%20Data%20Center%20Networking&CommCmd=MB%3Fcmd%3Dpass_through%26location%3Doutline%40%5E1%40%40.1dddee0b/0#selected_message
    Roble

  • Compare DB objects between different schemas

    Hi,
    I want to compare db objects beween 2 different schemas like QA and PROD.
    Please suggest me a tool that compares table definitions,stored procedures and other db objects between different schemas.

    Did you check the above video link which is shared?
    Yes I'd agree with you and also i faced these situations to check what objects i need to export from Dev to Quality ( to analyze what are already correct or what have to be imported again)
    Generally Quality & Prod are in sync.
    Also will be waiting along with you if anyone comments on any such tool.
    Regards,
    Krishna Tangudu

Maybe you are looking for