当我们查询数据的时候,把它存放到一个位置。以供页面显示。
1:使用***Map取代内置对象存放
public String query(){
ActionContext.getContext().put("categoryList", categoryService.query());
ActionContext.getContext().getSession().put("categoryList", categoryService.query());
ActionContext.getContext().getApplication().put("categoryList", categoryService.query()); return "index";
}
对应的页面的显示
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'index.jsp' starting page</title>
</head> <body>
<a href="${pageContext.request.contextPath }/category_update.action">访问update</a>
<a href="category_query.action">查询所有类别</a><br/>
<c:forEach items="${requestScope.categoryList}" var="category">
${category.id }|${category.type }|${category.hot}<br/>
</c:forEach><br/>
<c:forEach items="${sessionScope.categoryList}" var="gory">
${gory.id }|${gory.type }|${gory.hot}<br/>
</c:forEach><br/>
<c:forEach items="${applicationScope.categoryList}" var="category">
${category.id }|${category.type }|${category.hot}<br/>
</c:forEach><br/>
</body>
</html>
方案2:
利用接口implements RequestAware,ApplicationAware,SessionAware
package lw.shop.action; import java.util.Map; import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport implements RequestAware,ApplicationAware,SessionAware{
protected Map<String,Object> request;
protected Map<String,Object> session;
protected Map<String,Object> application;
@Override
public void setSession(Map<String, Object> session) {
this.session=session;
} @Override
public void setApplication(Map<String, Object> application) {
this.application=application;
} @Override
public void setRequest(Map<String, Object> request) {
this.request=request;
}
}
然后Action继承BaseAction就可以了。