• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check that a session attribute exists

 
Bryce Martin
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have in my web app a couple servlets. The first servlet sets a session attribute. Sometimes it doesn't set a session attribute. Is there a way to check if an attribute exists? Some sort of ???

Or should I just always set the attribute to "" if it is not needed? That way it is always created and then I can just check for no value?
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Bryce Martin
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ben. I though I could do it gonna save me lines and lines of code
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't already have a link to the API on your desktop, you should.

See:
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html#getAttribute(java.lang.String)


getAttribute

public java.lang.Object getAttribute(java.lang.String name)

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

Parameters:
name - a string specifying the name of the object
Returns:
the object with the specified name
Throws:
IllegalStateException - if this method is called on an invalidated session





 
Vishal Kumar Shaw
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bryce Martin wrote:I have in my web app a couple servlets. The first servlet sets a session attribute. Sometimes it doesn't set a session attribute. Is there a way to check if an attribute exists? Some sort of ???

Or should I just always set the attribute to "" if it is not needed? That way it is always created and then I can just check for no value?





May be you should use

String s = session.getAttribute("myAtribute").toString();
if ( s.equals( "null" ){
...........
}
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64959
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Kumar Shaw wrote:May be you should use :
[b]String s = session.getAttribute("myAtribute").toString();


No. That will cause a Null Pointer Exception if the attribute (scoped variable) is not set.





P.S. Your desire to help is appreciated, but why are you answering a question (an old one at that) that has already been correctly answered?
 
Vibhatha Lakmal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh! you saved my time.... Thanks...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic