【问题标题】:Remove session's previous set value删除会话的先前设置值
【发布时间】:2026-01-19 06:15:02
【问题描述】:

我有一个页面,里面有 3 张图片,所以现在当 单击要像这样设置会话属性的图像

<a href="voting.jsp"><img onclick="myfunction('image_one')" src="image_one.jpg"></a>
<a href="voting.jsp"><img onclick="myfunction('image_two')" src="image_two.jpg"></a>
<a href="voting.jsp"><img onclick="myfunction('image_three')" src="image_three.jpg"></a>
<script>
function myfunction(name)
    if(name='image_one')
        <% session.setAttribute("user","image_one") %>
    else if(name='image_two')
        <% session.setAttribute("user","image_two")%>
    elseif(name='image_three')
        <% session.setAttribute("user","image_three")%>
</script>

当我在voting.jsp 页面中使用 session.getAttribute 时,现在答案总是 image_three 为什么

【问题讨论】:

    标签: html jsp


    【解决方案1】:

    您正在尝试在 javascript/JQuery 函数中使用服务器端代码(scriptlet)。 Scriptlet 代码在服务器端执行,Web-Container(Tomcat 服务器)发送干净的 HTML 页面作为响应。

    所以基本上你在这里做错了。不能在 JavaScript 函数中设置会话。

    你可以在这个流程中工作: 1.设置任意变量的值,相应地选择图像。

    2.通过提交页面将此值发送到servlet,并通过您获得的相应值设置会话。

    Setting session variable using javascript。检查一下。

    【讨论】:

      【解决方案2】:

      在将值设置为会话之前删除会话值。

      <%  session.removeAttribute("user");
          session.setAttribute("user","image_one"); %>
      

      【讨论】: