java如何使用Struts 2在JSP中打印会话属性
以下是我所拥有的:
Java类(添加用户):
public String addUser() throws NoSuchAlgorithmException {
HttpSession currentSession = request.getSession();
User u = new User();
u.setUname(getUserName());
u.setPassword(StringHash(getUserPass()));
u.setUtype(getUserType());
plResponse = iUserDAO.addUser(u);
setActionMessage(plResponse.getMessage());
currentSession.setAttribute("actionMessage", this.actionMessage);
return SUCCESS;
}
Java类(添加关联):
public String saveAssoc() throws Exception {
HttpSession currentSession = request.getSession();
try {
plResponse = iUserDAO.saveUserAssoc(currentSession.getAttribute("selectedUser").toString(), countryId, langId);
refreshUserAssociations();
setActionMessage(plResponse.getMessage());
currentSession.setAttribute("actionMessage", this.actionMessage);
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
return SUCCESS;
}
JSP(两种情况相同):
<s:if test="actionMessage != null && actionMessage != ''">
<div class="successMessage">
<br/><s:property value="actionMessage"/>
</div>
<br />
</s:if>
我有两个将返回消息传递到页面的案例。添加用户后,以及添加用户关联后。在这两种情况下,参数都正确地传递给会话(我调试了代码),但它只在第一种情况下显示(添加用户)。第二个案例假装在会话中没有actionMessage
原因可能是什么
# 1 楼答案
实际上,第一个和第二个案例都没有显示来自会话的消息。它在值堆栈中寻找一个变量
在第一种情况下,有一个返回值的action属性getter。在第二种情况下,它可能不是相同的值
在action类中使用会话的正确方法是实现} interceptor 将会话映射注入action bean属性
SessionAware
,它通过^{然后使用该映射,而不是http会话。见How do we get access to the session
在JSP中,您可以从上下文访问会话对象
# 2 楼答案
要访问会话中存储的属性,请使用以下代码:
查看Accessing scoped objects in property tag 页面以查看更多详细信息