关于Struts 2.x的学习记录:
十二、标签与属性范围
在Struts 2.x里面,每一个JSP页面一定要与Action紧密连接在一起,尤其在Action进行了服务器端跳转之后,也同样可以直接利用标签访问这个人类中的私有属性
范例:定义一个新的Action
public class DeptAction extends ActionSupport {
private Dept mydept=new Dept();
public Dept getMydept(){
return mydept;
}
public String execute() throws Exception{
this.mydept.setDeptno(10);
this.mydept.setDname("研发部");
return "dept.show";
}
}
<action name="DeptAction" class="com.lyt.action.DeptAction">
<result name="dept.show">dept_show.jsp</result>
</action>
此时直接在Action里面设置了一个mydept的VO类对象,随后定义了对象的内容,并且让其跳转到了一个指定的页面,但是这个页面要使用标签输出内容
范例:定义dept_show.jsp页面
<body>
<h1>部门编号:<s:property value="mydept.deptno"/></h1>
<h1>部门名称:<s:property value="mydept.dname"/></h1>
</body>
这个时候所有的标签不需要做任何直接性的处理就可以找到跳转过来的Action本身所具备的内容
但是在编写代码的过程中,Struts 2.x这种将JSP与Action紧密连接的形式我们并不会习惯,因为大部分人都习惯于利用request属性传递操作
范例:利用request属性传递操作
public String execute() throws Exception{
Dept dept=new Dept();
dept.setDeptno(10);
dept.setDname("研发部");
ServletActionContext.getRequest().setAttribute("dept", dept);
return "dept.show";
}
此时的标签无法找到属性范围中的内容,那么如果要想在Struts 2.x的标签里面访问属性范围中的内容,则在访问前要加上“#范围名称”,例如“#request”表示request属性范围
范例:修改标签
<h1>部门编号:<s:property value="#request.dept.deptno"/></h1>
<h1>部门名称:<s:property value="#request.dept.dname"/></h1>
如果要想使用Struts 2.x的标签,就必须使用OGNL的表达式语言完成