如何在Java Servlet中使用session.setAttribute(“ id”,id)onclick按钮?

时间:2018-08-22 15:47:14

标签: java html servlets servlet-3.0 httpsession

我想在单击按钮时将id存储在httpsession中,以便可以在另一个servlet中使用它。

HttpSession session = request.getSession();
<button>
   <a href = "\"http://localhost:8080/WhatASap/createConversation\""
            + "style=\"text-decoration:none\""
            + "onclick=\"session.setAttribute(\"ID\","+ ID + ")\">
        Chat 
   </a>
</button>

当我单击时,httpsession中的按钮ID尚未设置。

1 个答案:

答案 0 :(得分:2)

您无法从javascript将变量添加到HttpSession中。您必须在servlet中进行操作。您在onclick下编写的任何内容都将由不了解您服务器的客户端浏览器的javascript引擎执行。


根据您的情况,将所有变量解析到createConversation servlet中。

<a href='http://localhost:8080/WhatASap/createConversation/?ID=<%= ID %>'>

下一步,在您的servlet中;

HttpSession session = request.getSession();
session.setAttribute("ID", request.getParameter("ID"));