会话属性访问并转换为int?
我已在 Servlet 中使用以下命令将用户 id 存储在会话中:
HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
现在,我想从另一个 Servlet 访问该用户 id:
HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working
OR
User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
问题:
- 如何转换为 int 并将 id 发送到 DAO 进行 SELECT 语句
I have stored user id in Session using following command in Servlet:
HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
Now, I want to access that user id from another Servlet:
HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working
OR
User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
Question:
- How can I cast to int and send the id to DAO for SELECT statement
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
即使您保存了
int
,该方法也需要一个对象,因此您的int
将由于自动装箱而变成Integer
。尝试将其转换回 Integer,应该没问题:但是,如果属性为 null,您将在此处得到 NullPointerException,所以也许最好使用
Integer
一路:之后,您可以安全地检查
userid
是否为null
。编辑:
为了回应您的评论,这就是我所说的“检查空值”的意思。
Even if you saved an
int
, that method expects an Object so yourint
will become anInteger
due to auto-boxing. Try to cast it back toInteger
and it should be fine:However, if the attribute is null you will get a
NullPointerException
here, so maybe it's better to go withInteger
all the way:After this, you can safely check if
userid
isnull
.EDIT:
In response to your comments, here's what I mean by "check for null".
我不擅长JAVA,但我曾经这样做过
Integer.parseInt(session.getAttribute("user").toString())
尝试一次,但一定要
检查 null
session.getAttribute(" user")
在调用toString
之前I'm not good at JAVA but I used to do it like
Integer.parseInt(session.getAttribute("user").toString())
Try once, but just be sure to
check null
forsession.getAttribute("user")
before callingtoString
Java 有
Integer
包装类,您可以将 int 值存储在Integer
的对象中Java has
Integer
wrapper class , you can store int value in an Object ofInteger
尝试 int userid = (Integer) session.getAttribute("user");
Try
int userid = (Integer) session.getAttribute("user");
我用过这个:
I used this:
试试这个
try this
试试这个,它对我有用:
HttpSession 会话 = request.getSession();
if (session.getAttribute("user") != null) {
userid = ((Integer) session.getAttribute("用户")).intValue(); } else { 用户ID = 0; }
try this, it worked for me:
HttpSession session = request.getSession();
if (session.getAttribute("user") != null) {
userid = ((Integer) session.getAttribute("user")).intValue(); } else { userid = 0; }
将会话中的两个字符串相乘:
Multiplying two strings from session:
试试这个代码:
Try this code :