【问题标题】:Display username in jsp redirected from a servlet在从 servlet 重定向的 jsp 中显示用户名
【发布时间】:2015-01-15 14:49:51
【问题描述】:

我知道这个问题已经被问了很多时间,但我真的不明白如何得到它。我做了一个小 servlet,在登录表单后,设置一个有状态会话 bean(检索实体)并将用户重定向到家。 Servlet 是这样工作的:

@EJB
private SessionCart ses;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
ses.login(email, password);
}

现在,SessionCart 有一个返回用户名的方法(该方法是 .getNome()),我想在用户被重定向到主页时通过 http 传递它。 我可以使用请求对象进行重定向,但我得到了主页(例如,我在 URL localhost:8080/web/form/login 中有 servlet,我在地址 localhost:8080/web/form/ 中得到了主页登录,但它可能在 localhost:8080/web/ 中,否则浏览器将无法识别图像和其他元素)。我怎样才能让它工作?

更新: 一些关于 @developerwjk 的 SessionCart 的代码

@Stateful
@LocalBean
public class SessionCart {

@Resource
private SessionContext context;
@PersistenceContext(unitName="ibeiPU")
private EntityManager manager;
private LinkedList<Vendita> carrello;
private LinkedList<Integer> quantita;
private Persona utente;
/*
* Business methods
*/
}

【问题讨论】:

  • 我尝试使用 response.addCookie(c) 设置一个 cookie,其中 c 是一个包含用户名的 cookie,但是浏览器在重定向后不会发送它:(
  • 您必须实际将您假定的会话 bean 放入会话中。仅将其命名为 SessionCart 不会将其放入会话中。
  • 保持专注。不要跳过整个地图。查找 HttpSession 以及如何使用它...不要转而尝试做 cookie,因为通过给一个包含“会话”一词的类命名,会话不会神奇地出现。
  • 我是 EJB 新手,如何将会话 bean 放入会话中?我用 netbeans 创建它(做新的会话 bean)

标签: jsp jakarta-ee servlets ejb-3.0


【解决方案1】:

您需要使用HttpSession 并从request 对象中获取会话,并将bean 放入其中:

private HttpSession session;
private SessionCart cart;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
{
  String email = request.getParameter("email");
  String password = request.getParameter("password");
  session = request.getSession();
  //I assume the cart was initialized somehow, maybe in the init() method
  cart.login(email, password);
  session.setAttribute("cartbean", cart);
  //there should be a redirect here to some other page
  response.sendRedirect("home");
}

然后在其他页面中,要检索购物车 bean,您可以这样做:

HttpSession session = request.getSession();
SessionCart cart = (SessionCart)session.getAttribute("cartbean");

【讨论】:

  • 会话bean不应该由容器自动相对于会话上下文吗?因为我正在读一本关于 j2ee 的书,但我从未见过这个
  • @Neo87,SessionCart 是你写的吗?也许您应该从那里发布一些代码,以使其更清楚它的作用。但基本上,除非SessionCart 的构造函数接受HttpSession,否则您必须这样做。但是,您可以将会话传递给 SessionCart 并让它将内容放入会话中。
  • @Neo87,点赞SessionCart cart = new SessionCart(request.getSession()),然后在购物车类中使用HttpSession。但是,要在下一页中引用 SessionCart 对象,您必须将 SessionCart 对象本身放入会话中,如上所示。
  • 使用 SessionCart bean 的声明部分进行编辑。无论如何,关于会话的建议,它工作得很好:)。我不明白为什么修改请求会更改会话中的数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2018-04-18
相关资源
最近更新 更多