File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes setAttribute & getAttibute doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "setAttribute & getAttibute doubt" Watch "setAttribute & getAttibute doubt" New topic

setAttribute & getAttibute doubt

Alvin chew
Ranch Hand

Joined: Jan 08, 2004
Posts: 834
hi, i have difficulty to understand of concept SetAttribute and getAttribute , can anyone please show me some sample code how is it work ? thank you very much for your time !!
John Dunn
Ranch Hand

Joined: Jan 30, 2003
Posts: 1108
class MyObject {
String name;
int count;
MyObject(String n, int c) { name = n; count = c; }

in your servlet:
MyObject myObj = new MyObject(one, 1);
request.setAttribute("MyObj", myObj); //now myObj is available in request
//get the request dispatcher and forward or include to your jsp

in your jsp, something like this:

//may need to import MyObj class definition...

<% MyObj myObj = (MyObj)request.getAttribute("MyObj"); %>

//Now you have access to the myObj object!!

"No one appreciates the very special genius of your conversation as the dog does."
Alvin chew
Ranch Hand

Joined: Jan 08, 2004
Posts: 834
so john, setAttribute is actually set the object to be available , getAttribute is to get object ...

from the above code, is that means we now call the object into page, so that we can now get the MyObj object members, like name and count ?

another question, why normally it use in request not response ?

thank you !!
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
because we dont have these methods.

response.setAttribute(String str, String str)
response.getAttribute(String str)

read the docs.
I agree. Here's the link:
subject: setAttribute & getAttibute doubt
It's not a secret anymore!