Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: What can I use instead of instance variables in a servlet?

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default What can I use instead of instance variables in a servlet?

    Hello, I have a program I want to convert into a servlet. When I use an instance variable; "count" in this case, it is one variable for many users and it does not reset to 0 each time the servlet is run.

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
     
    public class SimpleCounter extends HttpServlet {
     
      int count = 0;
     
      public void doGet(HttpServletRequest req, HttpServletResponse res) 
                                   throws ServletException, IOException
       {
     
        res.setContentType("text/plain");
        PrintWriter out = res.getWriter();
     
        count++;
     
        out.println("Count = " + count);
     
        }
     
    }

    This is a problem for me. I could use local variables instead but I have a problem with them too. Primitives are passed by value instead of by reference meaning if I change one, it will not effect the original's value. On top of this, I cannot return more than one variable at a time.

    I don't know the best way around this and I was hoping one of ya'll could help.

    Cheers
    Last edited by J05HYYY; February 17th, 2011 at 03:28 PM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: What can I use instead of instance variables in a servlet?

    Did you try the code you posted? The servlet life cycle might give you what you want...

  3. The Following User Says Thank You to copeg For This Useful Post:

    J05HYYY (February 18th, 2011)

  4. #3
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: What can I use instead of instance variables in a servlet?

    Yeah, I tested the code. Also, it's example 3.1 from here.

    With instance variables, all requests share one variable whereas with local variables it's on a per-thread basis... but what if I want my instance variables to be on a per-thread basis too, after all those are the variables which can be modified across all methods.

    Like I said before I could try using just local variables but primitives are passed by value instead of by reference, meaning that if I change one, it will not effect the original's value Also I think i'm correct in saying that in java, I cannot return more than one variable from a method at a time.

    Maybe I could create an object or something containing the primatives so's that I can change the original value but really I'm just guessing.

    There must be some elegant way of doing this.

  5. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: What can I use instead of instance variables in a servlet?

    I guess the more important question is what you want to do? If you are worried about threading, then synchronize access to the instance variable. If you want the data to survive server shutdowns, then persist the data to a database or file. Again, its about what you want to do.

  6. The Following User Says Thank You to copeg For This Useful Post:

    J05HYYY (February 18th, 2011)

  7. #5
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: What can I use instead of instance variables in a servlet?

    Okay, say I have the code below ...

    randomMethod can change instance variables "count" and "randomstr". Which is what I'm after.

    But my problem is that because they are instance variables, all requests share one variable (or two in this case).

    So I guess my question would be, how can I change them to be local variables and allow randomMethod to change them?

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
     
    public class SimpleCounter extends HttpServlet {
     
      int count = 0;
      String randomstr = "Hello world!";
     
      public void randomMethod()
      {
     
      count++;
      randomstr = "Goodbye world!";
     
      }
     
     
      public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
       {
     
        res.setContentType("text/plain");
        PrintWriter out = res.getWriter();
     
        randomMethod();
     
        out.println("Count = " + count + " , Random String = " + randomstr);
     
        }
     
    }

    I can't use return because there are two variables which need to be passed back. You get me?
    Last edited by J05HYYY; February 18th, 2011 at 02:36 PM.

  8. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: What can I use instead of instance variables in a servlet?

    One option would be to re-write the function: create a pojo (plain old java object) class that wraps the data, then pass an instance of this class to the function as a parameter and let the method do its work

  9. The Following User Says Thank You to copeg For This Useful Post:

    J05HYYY (February 18th, 2011)

  10. #7
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: What can I use instead of instance variables in a servlet?

    Hmm these POJO's seem complicated. I'm not so good with OOP as it is. Could I request some code on how to do this, or is that asking a little too much?

    [Maybe I would be better asking about this in a different place?]

  11. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: What can I use instead of instance variables in a servlet?

    Pojo = plain old java object.
    public class MyClass{
        private int value;
     
        public MyClass(int val){
            value = val;
        }
        public void setValue(int val){
            this.value = val;
        }
        public int getValue(){
            return value;
        }
    }

    In servlet
    public void myMethod(MyClass myClass){
        myClass.setValue(myClass.getValue + 1 );
    }

  12. The Following User Says Thank You to copeg For This Useful Post:

    J05HYYY (February 18th, 2011)

  13. #9
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: What can I use instead of instance variables in a servlet?

    I've been playing around with it and seems to work fine. I have never written more than one class before but it was pretty straight forward.

    I saved this as MyClass.java and compiled it into MyClass.class:

    public class MyClass{
        private int count;
        private String randomstr;
     
        public MyClass(int val, String valtwo){
            count = val;
    	randomstr = valtwo;
        }
     
        public void setIntValue(int val){
            this.count = val;
        }
        public int getIntValue(){
            return count;
        }
     
        public void setStringValue(String val){
            this.randomstr = val;
        }
        public String getStringValue(){
            return randomstr;
        }
    }

    And saved this as servlet.java and compiled it into servlet.class:

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
     
    public class servlet extends HttpServlet {
     
    	public void randomMethod(MyClass myClass)
    	{
    		myClass.setIntValue(myClass.getIntValue() + 1 );
    		myClass.setStringValue("Goodbye World!");
    	}
     
     
      	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    	{
     
    	MyClass myClass = new MyClass(0, "Hello World");
     
    	res.setContentType("text/plain");
    	PrintWriter out = res.getWriter();
     
    	randomMethod(myClass);
     
    	out.println("Count = " + myClass.getIntValue() + ", String = " + myClass.getStringValue());
     
    	}
     
    }

    Then placed both in the same folder and ran the servlet. Thankfully count did not increase as before. I think I will have problems with my ArrayLists (maybe not as those are supposedly passed by reference) but that's a different story.

    Cheers.
    Last edited by J05HYYY; February 18th, 2011 at 06:12 PM.

  14. #10
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: What can I use instead of instance variables in a servlet?

    Hello J05HYYY,

    By standard and according to the Servlet spec, servlets are not threadsafe, this means you shouldn't really use instance variables as there will only ever be one instance of that servlet (in most cases) and it will serve every request to it, simultaneously in different threads. There is a way to get around that of course and that is to set the servlet to be in Single Threaded Mode (NOT RECOMMENDED) but if you want to know more about that feel free to find out your self.

    What copeg is saying is definitely the way to go, just wrap your primitives or any other values in a wrapper class and pass that around instead.

    However I must say I fail to see how this count value will work for you as each time a request comes in you create a new MyClass object and set the count to zero and then you increment it by one and print that to the screen. You might want to consider using getServletContext or similar and use a setAttribute method to store your object away and then on a new request you do getAttribute and grab that object, increment the value of it and store it back again. This way the counter will start working and persist the value for as long as your application is up and running.

    You should also take note that this is not an atomic operation and hence result in miscalculation when many requests are coming in, it might need a synchronize block.

    myClass.setIntValue(myClass.getIntValue() + 1 );

    Hope any of this makes any sense

    // Json

  15. #11
    Junior Member
    Join Date
    Apr 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Cool Re: What can I use instead of instance variables in a servlet?

    The problem is you are trying to preserve state. That is, you are trying to maintain data either between requests for the same user (or perhaps shared among all users?)

    The Servlet is designed to be stateless. Meaning each time it runs it should not "remember" anything from any previous execution. The advantages of stateless classes are primarily performance and scalability. The best practice is to only use instance variables for read-only constants, which should be declared final.

    To persist state for a single user, store it in the session if it is small, else store it in a persistent store (like a database).

    To persist state to be shared among multiple users, you have other options. A singleton design pattern is useful as long as you understand there will be one per server. In other words many web applications are hosted on more than one server to offer high availability, so there will be a singleton on each server.

    If that does not meet your requirements, a database is probably your best bet. There are more complex solutions, like distributed cashes, as well.

Similar Threads

  1. Replies: 2
    Last Post: January 22nd, 2011, 11:20 PM
  2. Compare instance of a class to another
    By srs in forum Java Theory & Questions
    Replies: 5
    Last Post: December 2nd, 2010, 10:39 AM
  3. Address of String instance
    By American in forum What's Wrong With My Code?
    Replies: 3
    Last Post: September 6th, 2010, 02:20 PM
  4. [SOLVED] Help with classes & instance methods
    By ShakeyJakey in forum Object Oriented Programming
    Replies: 16
    Last Post: July 30th, 2010, 01:20 PM
  5. Creating new instance
    By vluong in forum Object Oriented Programming
    Replies: 2
    Last Post: November 28th, 2009, 11:35 PM