Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using the variable value of one class in another

 
namrata suri
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the same package, I have two classes.

In class 1, I declare a string variable and assign it some value.
After a few steps (i am using struts as well and the second class is called a while later), the program execution comes to class 2 and here I need the value of the string from class 1.

I tried set and get methods in class 1 for the string and tried accessing that in class 2 (but declaring a new instance of class 1 and then calling the get method returns NULL for the string).

I cannot make the string variable static also because it is formed of some components.

Please help.
 
D. Ogranos
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are developing a web application (since you say you use Struts), you may be able to pass objects and values via the request or session scope. These scopes are basically (java) Maps made available by the web container, to which you can add your values.
 
namrata suri
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These two classes in discussion are action classes and have no relation with each other.

Class 1 is called -> returns success -> a jsp is called (this contains a form whose values are accessed via the second class)

(this is the rough flow)

now how can class 2 access variable values in class 1.

I do not know much about sessions.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You appear to have a design problem in your class 1. Please show us more details.
 
D. Ogranos
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
namrata suri wrote:now how can class 2 access variable values in class 1.


You shouldn't access the first class at all from your second class.

Usually to transfer data from one action to another, you pass it via the session scope, or the request scope (which are represented through HttpSession, and HttpServletRequest). Both offer you methods getAttribute() and setAttribute(). Use those to save values in your first action class, then read them out again in your second.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like a servlet-specific question. Moving thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic