简体   繁体   English

如何将会话值从一个 servlet 检索到另一个 servlet?

[英]How to retrieve session value from one servlet to another servlet?

In one servlet I have four variables.在一个 servlet 中,我有四个变量。 I want all those four variables to be retrieved to another servlet.我希望将所有这四个变量检索到另一个 servlet。

I used the code in servlet 1 as follows.我使用了 servlet 1 中的代码,如下所示。

import javax.servlet.http.HttpSession;


session.setAttribute("id",id);

In the other servlet I tried to get the value by using the code..在另一个 servlet 中,我尝试使用代码获取值。

String id = HttpSession.getAttribute("id").toString();

I think there is a clear way to do the tracking of the session variables.我认为有一种明确的方法来跟踪会话变量。

I have seen in net but all are confusing to me..我在网上看到过,但都让我感到困惑..

Please help me..请帮我..

First you need to get the Session object from the request.首先,您需要从请求中获取 Session 对象。

This is the HTTPServletRequest object sent to the servlet (you will have access to this in the doGet or doPost method).这是发送到 servlet 的 HTTPServletRequest 对象(您可以在 doGet 或 doPost 方法中访问它)。

to set:设置:

ses = request.getSession(true);
ses.setAttribute("Name","Value");

to retrieve:检索:

request.getSession(false).getAttribute("name")

getSession(true) means create session if one does not exist. getSession(true)表示如果会话不存在则创建会话。 getSession(false) is equal to getSession. getSession(false)等于 getSession。 Finally if you wish to remove the attribute from the session from that point you can use最后,如果您希望从那时起从会话中删除该属性,您可以使用

request.getSession().removeAttribute("Name");

I hope this makes sense to you if you need more look at Java Set, Get and Remove Session Attributes .如果您需要更多地了解Java Set、Get 和 Remove Session Attributes,我希望这对您有意义。

TomRed汤姆红

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

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