Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

setAttribute & getAttibute doubt

 
Alvin chew
Ranch Hand
Posts: 834
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
slicker
Ranch Hand
Posts: 1108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!
 
Alvin chew
Ranch Hand
Posts: 834
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because we dont have these methods.

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

read the docs.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic