Communication between 2 servlets/java classes.

Hi,
I’ve a problem. Not sure if it’s a simple one.
I have a web app with servlets (say Servlet1, Servlet2, etc.) in it. I use a SQL query in Servlet1 and fetch an employee’s information (say empinfo) from the database. This is a string value. Now, I need to pass this “empinfo” to Servlet2.
I might sound dumb till here but please continue till the end to know what I still have to say…
1.     I tried using getters and setters. Servlet2 has the “empinfo” value I need. This is the first time Servlet2 is accessed.
2.     But, think that Servlet1 is transferring the control to an html page. And, this html page submits its parameters (say manager) to Servlet2. And, when this html passes its control to Servlet2, the “empinfo” value I need is gone because I used “empinfo” as a class member/global.
3.     So, when the control enters the Servlet2 the second time everything is lost and this is when I need the “empinfo” value.
4.     I cannot make the “empinfo” value in Servlet2 “static” because it keeps changing.
Note: I tried with all these: httpsession, reflection, etc. but nothing seems to fulfill my task.
Actually, Servlet2 lets the users to download the “empinfo” when a link on the html page (which sends the parameters to this servlet) is clicked.
I used httpsession to store this “empinfo” in Servlet1 and used to grab the value in Servlet2.
Then, I ran this app on my localhost. Then:
Step1: I opened up one browser and when I clicked the link on html, I checked the “empinfo” value. It was fine.
Step2: I opened up another browser and when clicked the link on html, I checked the “empinfo” value. It worked again.
Step3: Now, I went back to the html page in the browser1 and clicked the link and checked to see the “empinfo” value and now it has the value of that in browser2.
The “empinfo” always had the latest value. Previous values are overwritten.
If I could find a way to cache the Servlet1 object to use it in Servlet2 then I think my job is half done because even if I let Servlet2 keep a reference of the Servlet1, the html page is ruining the desired result.
If anyone can let me know how to do this with normal Java classes even that works for me.
Thanks in advance.

Thanks for the reply.
Actually, when I used the session the IE browser behaved properly and its the FireFox that was weird.
I think this is because Firefox uses single cookie for many instances of itself.
Thanks again.

Similar Messages

  • JSF 2.0: Interaction between several Java classes (get value)

    Hi Everybody!
    Unfortunately, I find both in the web and in books not really advice. And slowly I have the feeling that something is either really lazy or I'm just incapable! :-)
    Following scenario:
    Suppose I have a JSF page (.xhtml-file) that has several input fields (<h:inputText... />). For example, a field for the lastname (with the corresponding Java class: Customer.java) and a field for the ordered product (with the corresponding Java class: Shoppingcart.java). In addition, the page has a Save button to store the entered data into the database (with the corresponding Java class: Jdbc.java).
    Code of JSF page:
    <table>
      <tr>
        <td><h:inputText id="lastname" value="#{customer.lastname}" /></td>
      </tr>
      <tr>
        <td><h:inputText id="product" value="#{shoppingcart.product}" /></td>
      </tr>
      <tr>
        <td><h:commandButton action="#{jdbc.insertDataIntoDB}" value="Save" /></td>
      </tr>
    </table>Code of Customer.java class:
    @ManagedBean (name = "customer")
    @SessionScoped
    public class Customer
       private String lastname;
       public String getLastname()
          return lastname;
       public void setLastname(String lastname)
         this.lastname = lastname;
    }Code of Shoppingcart.java class:
    @ManagedBean (name = "shoppingcart")
    @SessionScoped
    public class Shoppingcart
       private String product;
       public String getProduct()
          return product;
       public void setProduct(String product)
         this.product = product;
    }Code of Jdbc.java class:
    @ManagedBean (name = "jdbc")
    @SessionScoped
    public class Jdbc
       public String insertDataIntoDB()
          Connection conn = null;
          Statement  stmt = null;
          try
             Class.forName("com.mysql.jdbc.Driver");
             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_xyz", "username", "pw");
             stmt = conn.createStatement();
             stmt.executeUpdate("INSERT INTO db_xyz.tbl_orders (Lastname, Product) VALUES (" + lastname + "," + product + ");");
    }Please ignore the last line (stmt.executeUpdate) of my code in the jdbc class. This does not work.
    And right here is just my problem!
    How do I get in my Jdbc class the current values of the entered lastname and product?
    I'll be very grateful if you could help me in this regard.
    Many greetings and thanks in advance.
    Edited by: Fools on Sep 13, 2010 5:48 AM

    One approach is to have a backing bean for each JSF. Say you have shoppingPage.jsf, you could also have a managed bean called ShoppingPage. If this bean holds references to the other beans then it is easy to reference everything via the first bean.
    class ShoppingPage {
         private DataBase db;
         private ShoppingCart sc;
         //getters and setters, etc
    }The JSF can refer to the ShoppingCart via the ShoppingCart i.e. #{ shoppingPage.sc.doSomeThing() }
    If both db and sc are involved then #{ shoppingPage.save() } where the save function is in the ShoppingCart object and can see both of the other objects.
    Otherwise it get a bit complicated because there may be several users on your website so you need to identify the objects relating to a particular user. Take a look at http://balusc.blogspot.com/2006/06/communication-in-jsf.html

  • Communication between servlet(client behavior) and stand alone java program

    Hello all:
    I need to send a message (ascii characters sequence) from a servlet to a java program, but I'm not sure what is the best way to get it: socket, JMS or other mechanism that I don't know.
    Is the servlet who is operating how client behavior.
    Please, any comment will be appreciated, regards,
    Ulises.

    You can always start a ServerSocket on the client (kinda sounds funny, doesn't it) which will accept connections. You then open a plain old Socket on the server to connect to the client's listener. (Note, this is the reverse of a normal set-up). Once you have the connection established, you will call getOutputStream() to get a stream to write to. Likewise, you will call getInputStream() to read the data sent. You will want to investigate the java.net.* and java.io.* libraries.
    - Saish

  • Communication between servlet & rich client - ObjectStream or OutputStream?

    Hi,
    I need to send a text file from a servlet to a rich client. Is it better to send it over OutpputStream or wrap it up as an Object(eg: StringBuffer) and send it over OutputStream?
    Will the performance be significantly be affected if I try to wrap the file into an object at the Servlet's end and send it over ObjectStream? We are planning to wrap all responses from the servlet into a generic response object (containing data, exceptions and error codes if any) and send it to the client
    Please advice. Thanks in advance!

    Using object streams will create some protocole overhead. But you can minimize the effect by using compression.
    Ex:- java.util.zip.GZIPOutputStream & GZIPInputStream
    If you have already decided to use a genaric responce object then it will be good to have a generic request object too that will make your communication more flexible.
    But remember when you are doing serialization you might get problems when having different java versions in different ends if your object structures use data structures provided by java API (Ex:- Collections). You can work arround this problem (In most cases) by implementing custom serialization using writeReplace and readResolve methods.

  • What ways of communication between two java apps you know?

    Hi all
    Lame (but not for me) question.
    I have two java applications (first is web-app unning on server (tomcat or JBoss) and second is a standalone java app). Both are running on different JVM and both have to communicate with each other quite often - but mainly: the second one is going to pass results of its work to the first one.
    What way of communication would you suggest?
    Ps. I'm free to choose frameworks and overall architecture.
    Regards
    Grzesiek

    YoungWinston wrote:
    Blimey. That's a question and a half; and the answer will likely depend on what you need to do/send.
    For straight messaging, there's JMS, but for more esoteric stuff you might want to involve a database, so you may want to look at JDBC (or even something like Hibernate). EJBs generally use servlets, or there's also straight HTTP, even raw sockets.
    I suspect to need to rein in your question a bit and come up with some specifics.
    Winston
    Edited by: YoungWinston on Jan 13, 2011 5:26 PM
    Too slow, as usual :-)So:
    Blimey. That's a question and a half; and the answer will likely depend on what you need to do/send.Plain text, just statements ;)
    For straight messaging, there's JMS, but for more esoteric stuff you might want to involve a database, so you may want to look at JDBC (or even something like Hibernate).Yes, JMS is what might solve my problem. Even if there will be any database(?), the only ones I would be considering are H2, Derby, HSQLDB.
    I suspect to need to rein in your question a bit and come up with some specificsA little more details? Ok....
    Firstly, ordinary user via web app creates text file, and when it's ready - starts second app in separate JVM (separate JVM is needed due to risk of OutOfMemoryError or any other crashes).
    Second app (standalone) is going to process this file (it might take hours/days/weeks) and inform web-app about his progress (about 5 messages per minute).
    Of course all those messages are going to be saved in log file/ database (log file should be easier way to go).
    Note that many standalone instances of second app are going to be run simultaneously (I think that this is the place to use some database - to store info about all instances: whether they finished successfully or not: eg. due to some crashes)
    Thanks for you time and effort
    All of You helped me already ;)

  • Problem sending a httprequest to a servlet java class

    i know that entering an URL like this in the browser can call the servlet class:
    http://www.xxxxxxxx.com/RequestHandler?action=showallitems
    but.....
    what codes do i need to send a httprequest to the servlet in java coding?
    thanks again.

    You mean like a normal Java code, not HTML, Request Dispatch, or something like that?
    If so, then you will want to use a URLConnection (HttpURLConnection). First, create a java.net.URL to the location you want. Then open a connection (which returns a URLConnection - if your URL uses an http protocol it will actually use an HttpURLConnection and can be casted).
    Use the methods in java.net.HttpURLConnection to adjust the headers, and parameters, and set up the method to use. Then get the input stream to commit the request and read the response from the server.
    Make sure you read the API for URLConnection and HttpURLConnection thoroughly. There are some quirks and specific order of events that need to be followed. Also read http://www.javaworld.com/javaworld/jw-03-2001/jw-0323-traps.html for info on how to properly use a URLConnection.

  • ObjectStream communication between servlet and rich client

    Hi,
    I need to send multiple objects from a servlet to a rich client.
    Is it possible to send 2 objects of different types at the same time - ie, a hashtable and a custom object by writing them one after another into the response's ObjectOutputStream?
    Also, if I have two vectors containing different object types, say a Vector of Strings and a Vector of custom objects, how do I read the ObjectStream at the client end to get these two objects? Do I read two Vectors from the ObjectInputStream and then check the contained object using instanceOf?
    In the above scenarios, is it better to wrap the entire set of objects with a serialized wrapper class and send that single object from the server to the client?
    Please advice. Thanks in advance!

    You can send any number of objects in a stream one after other. If they are in different types/classes then you have to be carefull when casting to the specific types at the other end becouse if you try to cast to wrong type you get a runtime exception.
    Normally when you receive the objects you will know in advande (programming time) which vector comes first in the stream so you can treat them acordingly.
    Since both of them are vectors you can cast them to vector references at the read end and can tread the elements of the first vectors as strings and the elements of the other vectors as something else provided that the client always send the string vector first.
    Whether to make it a single object or ot is a design decision that you have to make. It it make sence to put those two vectors together(logically related) then its better to do so.

  • Communication between servlets with data

    I have a servlet that creates a HTML table (a report) with some data. The data used is a vector of some java objects. Now, I want to add a hyperlink to each row in the table and when clicked, open a new browser window and show the record info in detail. I know how to add a hyperlink and open a new window, but I do not know how to pass the data associated with that (user-clicked) row to a new browser window. The Java object for that row contains 20 items and I do not want to pass them in name-value pair to another servlet. Is there a smarter way to do this ? Can someone please help me?
    This is a rough sketch of how I want to put a hyperlink in a row: The following method creates rows in my table:-
    private void loadTableData(Vector data, PrintWriter out, int col)
            throws IOException {
            MyRecordObject myRec = null;
            if (data != null) {
                Object[] myArray = null;
                myArray = new Object[data.size()];
                for (int k = 0; k < data.size(); k++) {
                    myArray[k] = data.get(k);
                Arrays.sort(myArray, new MySorterClass(col));
                for (int i = 0; i < myArray.length; i++) {
                    myRec = (MyRecordObject) myArray;
    out.println("<TR bgcolor= \"E5E5E5\"> ");
    // When the following hyper link
    //is clicked, pass "myRec" object to some servlet/JSP
    //and create a new HTML page with that data
    out.println("<TD> <a href=\"myDetailInfoServlet_with_data\" target =\"_blank\"> " + myRec.getName() + " </a> </TD>"); // <==
    out.println("<TD>" + myRec.getFathersName() + "</TD>");
    out.println("<TD>" + myRec.getMothersName() + "</TD>");
    out.println("<TD>" + myRec.getPetName() + "</TD>");
    out.println("<TD>" + myRec.getSpouseName() + "</TD>");
    out.println("</TR>");
    out.println("</TBODY>");
    out.println("</TABLE>");
    out.println("</div>");
    out.println("</html>");

    My approach would be to just pass along an id with the hyperlink. Something you use to identify which record you want to display. This can be the recordId, or maybe the index of it in the data vector if that is still available and hasn't changed.
    eg
    out.println("...<a href=\"myDetailInfoServlet_with_data\?id= " + i + " ...
    Also, I would recommend using JSPs for this sort of stuff.
    For sure, retrieve your data in a servlet, but then just put it into request/session variables, and forward to a JSP to display.
    using out.println for table code is a real pain in the butt.
    Cheers,
    evnafets

  • Communication between servlet & applet

    Hello everybody,
    Well, I have a problem with my applet/servlet system.
    I Would like my applet to send some queries to the servlet.
    However, I don't know how to link the applet with the servlet (the only way I know is to use "openConnection()", but I don't see how to incorporate my query in the URLConnection (in order to have one, I need openCOnnection, and once it's done, well, the doGet method has already be laucnh, without any parameter to read). In my case, the DoGet methods of the servlet is launched, and of course, the HTTPRequest is almost empty, seeing thath I don't see how to specify the differnets parameters.
    Is thereany simple meaning to make the applet communicate this the servlet, sending strings, and receiving objects (I have already solve the problem of the sending of an object from the servlet to the applet, in the doGet method).
    Thank you very much
    C U

    In the applet html include a servlet parameter.
    <param
    name="servlet"
    value="/SqlServlet" />
    In your applet open a connection to servlet.
    InputStream in = null;
    URLConnection conn = null;
    URL url = null;
    String servlet = getParameter("servlet");
    url = new URL(servlet + "?sql=" + URLEncoder.encode(sql));
    conn = url.openConnection();
    in = conn.getInputStream();

  • Communication between seperate java programs

    I'll briefly explain what I am trying to achieve, it should make things more transparent when it comes to my problem...
    I have a database file (db4o .yap file) which contains several thousand strings and is constantly updated. This database needs to be accessed by more than 1 program at any one time. (In my case the database holds URLs as Strings and several "web crawler" programs accesses the database to request a new URL to crawl).
    My problem is once one web crawler program connects to the database, it obtains a lock and prevents other web crawler clients from gaining access to the database.
    What I would like to implement is a "database manager" program which is constantly running and creates a single connection to the database. This would then "wait" for calls/requests from the web crawler clients and return a single URL.
    This way, only the "database manager" would have direct access to the database.
    So is there an easy way for a "web crawler" program to "call/request" a URL from the "database manager" program?
    I hope I have explained the problem enough, if I havent and have just confused you let me know!
    Many thanks...

    Thanks for your reply.
    I have read around the topic regarding reading and
    writing to a socket as explained here:
    http://java.sun.com/docs/books/tutorial/networking/soc
    kets/readingWriting.html
    However having played around with the code am I right
    in thinking when you use sockets you need to two
    computers on a network, one being the "client" and
    one being the "server"?No. You can have both the "client" and the "server" on the same machine.
    >
    What I really need at this point is to use one single
    machine and on it have ONE program runnning
    constantly, the "database manager" which just waits
    for requests by the "web crawler" clients. When a
    call to the database manager is made it returns a URL
    to the web crawler client.
    That can be done with sockets. (See ServerSocket).
    Ideally I would like to have another machine
    connected to my network to deal with the multiple
    requests to the database but at present I just need
    the above to work.
    Let me know if i've totally misunderstood you ;)

  • Difference between Java class and JavaBean?

    What is the difference between a Java class and a JavaBean?
    A class has variables which hold state.
    A class has methods which can do things (like change state).
    And if I understand a JavaBean it is rather like a BIG class...
    i.e.
    A JavaBean has variables which hold state.
    A JavaBean has methods which can do things (like change state).
    So, what's the difference between the two?
    And in case it helps...What is the crossover point between the two? Is there a minimalist type JavaBean which is the same as a class? What is the difference between Java beans and Enterprise Java Beans?
    Thanks.

    Introspection, as I understand it is a bunch of
    methods which allows me to ask what a class can do
    etc. right? So, if I implement a bunch of
    introspection methods for my class then my class
    becomes a JavaBean?Introspection allows a builder tool to discover a Bean's properties, methods, and events, either by:
    Following design patterns when naming Bean features which the Introspector class examines for these design patterns to discover Bean features.
    By explicitly providing the information with a related Bean Information class (which implements the BeanInfo interface).
    I understand now they are completely different.
    Thanks. Very clear.
    I do not understand how they are completely different.
    In fact I don't have a clue what the differences are
    other than to quote what you have written. In your
    own words, what is the difference? This is the "New
    to Java Technology" forum ;-) and I'm new to these
    things.In that case ejbs are way too advanced for you, so don't worry about it.

  • Difference b/w Java Class and Bean class

    hi,
    can anybody please tell me the clear difference between ordinary java class and java Bean class. i know that bean is also a java class but i donno the exact difference between the both.
    can anybody please do help me in understanding the concept behind the bean class.
    Thank u in advance.
    Regards,
    Fazlina

    While researching this question, I came across this answer by Kim Fowler. I think it explains it better than any other answer I have seen in the forum.
    Many thanks Kim
    Hi
    Luckily in the java world the definition of components is a little
    less severe than when using COM (I also have, and still occasionaly
    do, worked in the COM world)
    Firstly there are two definitions that need to be clarified and
    separated: JavaBean and EnterpriseJavaBean (EJB)
    EJB are the high end, enterprise level, support for distributed
    component architectures. They are roughly equivalent to the use of MTS
    components in the COM/ COM+ world. They can only run within an EJB
    server and provide support, via the server, for functionality such as
    object pooling, scalability, security, transactions etc. In order to
    hook into this ability EJB have sets of interfaces that they are
    required to support
    JavaBeans are standard Java Classes that follow a set of rules:
    a) Hava a public, no argument constructor
    b) follow a naming patterns such that all accessor and modifier
    functions begin with set/ get or is, e.g.
    public void setAge( int x)
    public int getAge()
    The system can then use a mechanism known as 'reflection/
    introspection' to determine the properties of a JavaBean, literally
    interacting with the class file to find its method and constructor
    signatures, in the example above the JavaBean would end with a single
    property named 'age' and of type 'int' The system simply drops the
    'set' 'get' or 'is' prefix, switches the first letter to lower case
    and deduces the property type via the method definition.
    Event support is handled in a similar manner, the system looks for
    methods similar to
    addFredListener(...)
    addXXXListener
    means the JavaBean supports Fred and XXX events, this information is
    particularly useful for Visual builder tools
    In addition there is the abiliity to define a "BeanInfo' class that
    explicitly defines the above information giving the capability to hide
    methods, change names etc. this can also be used in the case where you
    cannot, for one reason or another, use the naming patterns.
    Finally the JavaBean can optionally - though usually does - support
    the Serializable interface to allow persistence of state.
    As well as standard application programming, JavaBeans are regularly
    used in the interaction between Servlets and JSP giving the java
    developer the ability to ceate ojbect using standard java whilst the
    JSP developer can potentially use JSP markup tags to interact in a
    more property based mechanism. EJB are heaviliy used in Enterprise
    application to allow the robust distribution of process
    HTH.
    Kim

  • Comparison insertion/search time between different Collection class

    Hi,
    Does someone know where I can find a clear an complete comparison between different JAVA class which implements interface Collection?
    I want to compare:
    - elements insertion time
    - elements search/removal time
    Thank you very much in advance
    Diego

    from wikipedia: Its purpose is to characterize a function's behavior for very large (or very small) inputs in a simple but rigorous way that enables comparison to other functions.
    meaning if I ask how quick an algorithm is you might say it completes in 10 seconds but the next time you run it it might take 8 seconds. It kind of depends on what else your computer is doing/ how fast your computer is or how much data you are putting through ie if the puter has little memory it might need to use virtual memory which will have an effect on your performance.
    Big O notation identifies how much work has to be carried out. The easiest example is a simple search of an array:
    for (int i = 0; i < array.length; i++) {
      if (array[i] == "weijewr") {
        return i;
    }Where n represents a number of elements:
    This takes O(n) (big Oh of N) as potentially you need to look at each element.
    if you were to write a standard bubble sort it would be O(n2) as potentially you need to iterate the array once for each element.

  • Standard Java class communicating with a servlet

    Hey,
    I am trying to access a standard java classes member via a servlet class however the data is never received even though the member is visible on compilation. is there something Im doing wrong ?
    public class Start {
    //lots of stuff
         static List<Plug> plugList = Collections.synchronizedList(new LinkedList<Plug>());
    //lots more stuff
    public class wah extends HttpServlet{
            public void doGet( HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
                    doPost(request, response);
        public void doPost(HttpServletRequest request,
                                    HttpServletResponse res)throws ServletException, IOException{
                    res.setContentType("text/html");
                    PrintWriter out = res.getWriter();
                    out.println("wahwahwah");
                    synchronized(Start.plugList){
                            out.println("pluglist");
                            Iterator i1 = Start.plugList.iterator();
                            while (i1.hasNext()) {
                                    Plug oldPlug = (Plug)i1.next();
                                    out.println("PLug : " + oldPlug.getaddress64());
            }//doPost
    }

    Don't post all your code. Instead, make a simplified version of the code that demonstrates what your problem is and that we could compile and see what is going on. Make it as simple as possible but still demonstrating the problem.
    Who knows, when you make the SSCCP (small, self contained, compileable program) you will find your mistake as well.
    But without seeing any code all I can say is that the date you are accessing in the list has not been made available when you try to get it from the servlet. Perhaps the servlet call is blocking the other threads from accessing the list to put data into it, perhaps the other threads haven't begun working yet, perhaps the list you give to the servlet isn't the same list (but instead a copy of the list) that the data is being entered into, or many other reasons.
    One thing I would assume you need to do, since the Servlet is the data consumer, you need to make sure the data has been entered before the servlet tries to read it. The best way to do that is to put a wait() in the servlet code so that it knows it can't do anything until the producers are finished. Then the producers would add a notify() to tell the servlet to go ahead and display the data.
    So some modification might be:
    public class Start {
    //lots of stuff
         static List<Plug> plugList = Collections.synchronizedList(new LinkedList<Plug>());
            //marker to let servlet know that it can consume data
            private static boolean done = false;
            //producers call this method when list is ready for use
            static void setReadyToConsume() { done = true; }
            //servlet calls this to check if the list is ready
            public static boolean isReadyToConsume() { return done; }
    //lots more stuff
        public void doPost(HttpServletRequest request,
                                    HttpServletResponse res)throws ServletException, IOException{
                    res.setContentType("text/html");
                    PrintWriter out = res.getWriter();
                    out.println("wahwahwah");
                    synchronized(Start.plugList){
                           //Hold off trying to use list until list is ready
                            while (!Start.isReadyToConsume()) {
                                  try {
                                          Start.plugList.wait();
                                  } catch (InterruptedException ie) {
                                          log("Waiting for Plugs to be ready interrupted.  Continuing to wait.");
                                          log(ie.getMessage(), ie);
                            out.println("pluglist");
                            Iterator i1 = Start.plugList.iterator();
                            while (i1.hasNext()) {
                                    Plug oldPlug = (Plug)i1.next();
                                    out.println("PLug : " + oldPlug.getaddress64());
            }//doPostAnd don't forget to add a Start.plugList.notify() or Start.plugList().notifyAll() in the producer code after it calls the setReadyToConsume() method.

  • Palin old java class Servlet Communication issue

    I am sending data to servlet and able to get back data to plain old java class using url.openConnection mechanism.But I want to redirect another jsp page after servlet get data from java calss.
    Can any one help me please
    Regards
    Madhu

    What alternative could there be?
    You're calling a webserver which just happens to be running a Java process to generate its output.
    You don't have to know that, that's the whole point in using servlets...
    So no, there's no way (and if there is it's a terrible breach in the security of your server).

Maybe you are looking for