在 jsp 中显示从 servlet 重定向的用户名

Display username in jsp redirected from a servlet

我知道这个问题已经被问了很多次,但我真的不明白如何得到它。我做了一个小 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/login,但它可能在 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
*/
}

您需要使用 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");