我知道这个问题已被问了很多时间,但我真的不明白如何得到它。我创建了一个小servlet,在登录表单后,设置一个有状态会话bean(检索实体)并将用户重定向到home。 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()),我希望在用户被重定向到home时将其传递给http。 我可以使用请求对象重定向,但我得到了主页(例如我在URL localhost:8080 / web / form / login中有servlet,我在地址localhost:8080 / web / form /中获取主页登录,但它可能在localhost:8080 / web /或浏览器将无法识别图像和其他元素)。我怎么能让这个工作?
更新: 有关SessionCart for @developerwjk的一些代码
@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
*/
}
答案 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");