1、访问或添加request/session/application属性(此种方式适合仅仅是往3个范围放入属性)
public String execute() {
//此种方式适合仅仅是往3个范围放入属性
ActionContext act = ActionContext.getContext();
act.getApplication().put("app", "application范围");//往ServletContext里放入app
act.getSession().put("ses", "session范围");//往session里放入ses
act.put("req", "request范围");//往request里放入req
act.put("names", Arrays.asList("老张","老王","老于"));//将集合放入
return "success";
}
引入jstl.jar和standard.jar
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
${applicationScope.app }<br>
${sessionScope.ses }<br>
${requestScope.req }<br>
==========================================<br>
<c:forEach items="${names}" var="name">
${name } <br>
</c:forEach>
2、获取HttpServletRequest/HttpSession/ServletContext/HttpServletResponse对象
方法一:通过ServletActionContext类直接获取(适用获取站点目录下某文件的绝对路径)
public String rsa() {
//此种方式适合获取站点目录下某文件的绝对路径
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContent = ServletActionContext.getServletContext();
request.setAttribute("req", "请求范围属性");
request.getSession().setAttribute("ses", "会话范围属性");
servletContent.setAttribute("app", "应用范围属性");
System.out.println(servletContent.getRealPath("HelloWorld.java"));//HelloWorld.java的绝对路径
// HttpServletResponse response = ServletActionContext.getResponse();
return "success";
}
方法二:实现指定接口,由struts运行时注入
public class HelloWorldAction implements ServletRequestAware,ServletResponseAware,ServletContextAware {
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
@Override
public void setServletContext(ServletContext ser) {
this.servletContext = ser;
}
@Override
public void setServletResponse(HttpServletResponse rpo) {
this.response = rpo;
}
@Override
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
public String rsa() {
request.setAttribute("req", "请求范围属性");
request.getSession().setAttribute("ses", "会话范围属性");
servletContext.setAttribute("app", "应用范围属性");
return "success";
}
}