- 动作类是多例的,每次动作访问,动作类都会实例化。所以是线程安全的。
- 在每次动作执行前,核心控制器StrutsPrepareAndExecuteFilter都会创建一个ActionContext和ValueStack对象。且每次动作访问都会创建。
- 这两个对象存储了整个动作访问期间用到的数据。
- 并且把数据绑定到了线程局部变量(ThreadLocal)上了。所以是线程安全的。
contextMap

使用 struts内置标签
查看contextMap数据
利用ActionContext存数据
import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.ServletActionContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Map; / * @program: struts2_06 * @description * @author: LIANG * @create: 2021-02-02 13:20 / public class Actiondata extends ActionSupport {
@Override public String execute() throws Exception {
//获取ActionContext对象 直接存储key value对象 ActionContext contextMap = ActionContext.getContext(); contextMap.put("username","contextMapLIANG"); //获取session对象 催出数据 Map<String, Object> session = contextMap.getSession(); session.put("username","session01LIANG"); //通过request对象获取session 存储数据 HttpSession session1 = ServletActionContext.getRequest().getSession(); session1.setAttribute("username","seeeion02LIANG"); //获取request对象 存储数据 HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("username","requestLIANG"); //获取application对象存储数据 Map<String, Object> application = contextMap.getApplication(); application.put("username","application01LIANG"); //通过ServletActionContext获取Application对象 存储数据 ServletContext servletContext = ServletActionContext.getServletContext(); servletContext.setAttribute("username","application02LIANG"); return SUCCESS; } }

获取ValueStack对象的方法&存数据
//1 使用ActionContext对象获取 ValueStack valueStack = ActionContext.getContext().getValueStack(); valueStack.push(new Student("LIANG","")); //获取数据 方法一用ActionContext对象获取Request 获取值栈 Map<String,Object> requestMap = (Map<String,Object>)ActionContext.getContext().get("request"); ValueStack valueStack1 = (ValueStack)requestMap.get("struts.valueStack"); //第三种获取值栈的方法 使用ServletActionContext获取request 获取值栈 ServletActionContext.getRequest().getAttribute("struts.valueStack");
获取数据
取contextMap中的数据 需使用#
<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
@program: struts2_06
@description
@author: LIANG
@create: 2021-02-02 16:14
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html> <head> <title>data01
title>
head> <body> <s:debug>
s:debug> <%-- 取contextMap中的数据 使用#号--%> <s:property value="#username">
s:property><br> <s:property value="#session.username">
s:property><br> <s:property value="#application.username">
s:property><br>
body>
html>
获取valueStack中数据 直接写类中的属性名
<%-- 取contextMap里面ValueStack中对象的属性: 直接写对象中的属性名--%> <s:property value="username">
s:property><br>
当取valueStack数据时如果对象属性重名(如下图) 通过OGNL表达式查找

<s:property value="[0].password">
s:property><br> <s:property value="[1].password">
s:property><br>
注:当标签
不给value属性时 默认取ValueStack取栈顶元素
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/216572.html原文链接:https://javaforall.net
