7

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.

user2168435
  • 732
  • 2
  • 10
  • 27

3 Answers3

13

You have to cast it to String

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

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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)

Community
  • 1
  • 1
Stout Joe
  • 324
  • 2
  • 4
  • 14
-2

you just put like this:

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

append as string, simple.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
007
  • 115
  • 1
  • 13