Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsp unable to put session attribute into string

Tags:

java

jsp

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.

like image 757
user2168435 Avatar asked Jul 09 '13 10:07

user2168435


2 Answers

You have to cast it to String

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

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

like image 191
Suresh Atta Avatar answered Oct 26 '22 18:10

Suresh Atta


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)

like image 28
Stout Joe Avatar answered Oct 26 '22 19:10

Stout Joe