简体   繁体   English

jsp无法将session属性放入字符串

[英]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, 我在jsp页面中遇到会话属性的问题,我想将其传递给字符串,以便我可以使用它来查询数据库,例如,

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 类型不匹配:无法从Object转换为String

is there a different way to put a session variable into a String? 是否有将会话变量放入String的不同方法? or am i doing it completely wrong. 或者我完全错了。 any assistance much appreciated. 任何援助非常感谢。

You have to cast it to String 你必须把它StringString

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

where session.getAttribute("group"); 其中session.getAttribute("group"); returns Object . 返回Object

session.getAttribute(String name) will return an Object . session.getAttribute(String name)将返回一个Object

To be safe and prevent any accidental ClassCastException , I would use String.valueOf(Object obj) , like this: 为了安全并防止任何意外的ClassCastException ,我会使用String.valueOf(Object obj) ,如下所示:

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

Sources: 资料来源:

Difference between casting to String and String.valueOf 转换为String和String.valueOf之间的区别

http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#getAttribute(java.lang.String) 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) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)

you just put like this: 你就是这样说的:

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

append as string, simple. 追加为字符串,简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM