user2168435
user2168435

Reputation: 762

jsp unable to put session attribute into string

i'm having an issue with a session attriblute in a jsp page, i would like to pass it into a string so that i can use it to query a database eg,

String group=session.getAttribute("group"); 

i know it has been correctly populated because if i put the below in a page it displays the correct value

<%=
session.getAttribute("group")
 %>

the error i am getting is

Type mismatch: cannot convert from Object to String

is there a different way to put a session variable into a String? or am i doing it completely wrong. any assistance much appreciated.

Upvotes: 7

Views: 26525

Answers (3)

007
007

Reputation: 115

you just put like this:

String group=""+session.getAttribute("group"); 

append as string, simple.

Upvotes: -2

Stout Joe
Stout Joe

Reputation: 334

session.getAttribute(String name) will return an Object.

To be safe and prevent any accidental ClassCastException, I would use String.valueOf(Object obj), like this:

String group = String.valueOf(session.getAttribute("group"));

Sources:

Difference between casting to String and String.valueOf

http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#getAttribute(java.lang.String)

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

You have to cast it to String

String group=(String)session.getAttribute("group"); 

where session.getAttribute("group"); returns Object.

Upvotes: 13

Related Questions