java - JSP 中调用 session 属性

标签 java jsp session

我目前有以下内容:

HttpSession session = request.getSession();         
String discountError = (String) session.getAttribute("discountError");

if (discountError.equals("true")){
    session.setAttribute("discountAdded", "false");
    forwardPage = "DiscountEnd.jsp";

}
else if (discountError.equals("false")){
    session.setAttribute("discountAdded", "true");
    forwardPage = "Confirm.jsp";                
}

JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page session="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
          "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Discount(s) Added Successfully</title>
</head>

<body>

<c:choose>
    <c:when test="${discountAdded == 'true'}">
        <p align="center">  
            All Discount(s) added successfully!     
        </p>
    </c:when>
    <c:when test="${discountAdded == 'false'}">
        <p align="center">
            Error Found! No Discounts added!
        </p>
    </c:when>
</c:choose>

<br>
<form action='HotelOwnerController' method='POST' style="text-align:center">
    <input  type="submit" name="action" value="Back to Welcome Screen"/>
</form>

当我进入 JSP 页面时,我发现 discountAdded if 条件未得到评估。

有人知道如何读取 JSP 页面中的 session 属性吗?

最佳答案

不,当在 jsp 页面中捕获 session 变量时,它采用“Object”数据类型。我们必须将它们解析为字符串。为此,我们可以使用 .toString() 方法,也可以使用

进行转换
String str=(String)session.getAttribute("session_name");

或者

String str=(String)session.getAttribute("session_name");

对于您的代码,我建议使用sessionScope

<c:choose>
<c:when test="${sessionScope.discountAdded == 'true'}">
    <p align="center">  
        All Discount(s) added successfully!     
    </p>
</c:when>
<c:when test="${sessionScope.discountAdded == 'false'}">
    <p align="center">
        Error Found! No Discounts added!
    </p>
</c:when>

关于java - JSP 中调用 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23578770/

相关文章:

java - PhoneGap 3.1 Android 将音频文件从 www 文件夹复制到 SD 卡

java - 在 JSP 中显示多个图像的最佳方法

java - Struts 迭代器在另一个迭代器内

java - 从 tomcat 8.0 迁移到 8.5 时出现 ElException

php - 使用 Yii session 进行负载均衡

c# - 在 ASP.NET 中处理从多个 session 到数据库的多个插入

java - 在 Java 中查找 int 子数组的补充

java - 在java中将字符串转换为System.Decimal

java - GAE session 。 java.io.NotSerializedException : sun. nio.cs.UTF_8 问题

java - Eclipse/Maven 错误 : "No compiler is provided in this environment"