Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

session.getAttribute problems

Status
Not open for further replies.

Ricjd

Programmer
Sep 12, 2002
104
GB
I have some code which see if a session attribute has a value, but it is throwing up a "NullPointerException" error. My code is below.

[tt] //problems with this
String testLang = (String)session.getAttribute("lang");
if (testLang.equals(null))
{
session.setAttribute("lang", "English");
testLang = "English";
}[/tt]

Is there a way to find is a session attribute is set, then if not set it?

Thanking you in advance

Rick
 
I would do this

Code:
String testLang;
if(session.getAttribute("lang") == null){
   session.setAttribute("lang", "English");
   testLang = "English";
} else {
   testLang = session.getAttribute("lang");
}

Do the null test first before you access it as a string.
 
Hey

Thnaks for that

you've just saved me from failing my uni course.

now i think about it, it seems easy.

thanks again.
 
I beat my head against the wall multiple times on this same exact issue, now its tatooed into my brain :)

 
Rick,

to alter your original code only slightly (and access the session attribute only once... for whatever that's worth), I believe this would work:

Code:
//problems with this
    String testLang = (String)session.getAttribute("lang");
    if ([b]testLang == null)[/b])
    {
        session.setAttribute("lang", "English");
        testLang = "English";
    }

If testLang were null, then trying to use it as an object (as when you try the '.equals(...)' method on it) throws the NullPointerException.

'sounds like you got it working anyway.

Good luck with your final!

--Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top