*
The moose likes Struts and the fly likes Using the variable value of one class in another Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Using the variable value of one class in another" Watch "Using the variable value of one class in another" New topic
Author

Using the variable value of one class in another

namrata suri
Ranch Hand

Joined: Oct 22, 2009
Posts: 31
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

Joined: Feb 02, 2009
Posts: 214
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

Joined: Oct 22, 2009
Posts: 31
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

Joined: Oct 13, 2005
Posts: 38511
    
  23
You appear to have a design problem in your class 1. Please show us more details.
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
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

Joined: Oct 13, 2005
Posts: 38511
    
  23
Sounds like a servlet-specific question. Moving thread.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Using the variable value of one class in another