JSTL从会话中获取对象

时间:2014-06-14 22:56:17

标签: jsp session struts2 jstl

我在会话中放了一个对象:

session.setAttribute("userDTO", currentUser);

我正在尝试使用EL显示它。我已成功使用scriplets(证明对象在会话中设置正常)。

JSP中的代码:

<body>
    <% UserDTO userdto=(UserDTO)session.getAttribute("userDTO"); %>
    <%=userdto.getUsername() %>
    Username from session:<c:out value="${sessionScope.userDTO.username }"/>
</body>

scriplets显示用户名,但“会话用户名:”后没有显示任何内容。为什么呢?

UserDTO课程:

public class UserDTO {
    private int ID;
    private String email;
    private boolean emailConfirmed;
    private String username;
    private String role;
    public int getID() {
        return ID;
    }
    public void setID(int iD) {
        ID = iD;
    }
    public boolean isEmailConfirmed() {
        return emailConfirmed;
    }
    public void setEmailConfirmed(boolean emailConfirmed) {
        this.emailConfirmed = emailConfirmed;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

2 个答案:

答案 0 :(得分:3)

在JSP中,您只需使用表达式(称为EL - 表达式语言) -

即可
<body>
  Username from session : ${sessionScope.currentUser}
</body>

答案 1 :(得分:0)

第1步:jstl-x.x.jar放入lib文件夹或将依赖项置于maven中。

第2步:jsp档案

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 ...
 <body>
     <% UserDTO userdto=(UserDTO)session.getAttribute("userDTO"); %>
     <%=userdto.getUsername() %>
     Username from session:<c:out value="${sessionScope.userDTO.username }"/>
      ...
 </body>