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.
You have to cast it to String
String group=(String)session.getAttribute("group");
where session.getAttribute("group");
returns Object
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With