1 标签与属性范围
在Struts 2.x里面,每一个JSP页面一定要与Action紧密联系在一起,尤其是在Action进行了服务器端跳转之后,也同样可以直接利用标签访问这个类中的私有属性。
范例:定义一个新的Action
package org.lks.action;
import org.lks.vo.Department;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class DepartmentAction extends ActionSupport {
private Department department = new Department();
public Department getDepartment() {
return department;
}
@Override
public String execute() throws Exception {
this.department.setDid(1001L);
this.department.setDname("设计部");
this.department.setDlocation("米兰");
return "department.show";
}
}
<action name="DepartmentAction" class="org.lks.action.DepartmentAction">
<result name="department.show">department_show.jsp</result>
</action>
此时直接在Action里面直接设置了一个department的VO类对象,随后定义了对象的内容,并且让其跳转到了一个指定的页面,但是这个页面要使用标签输出内容。
范例:定义department_show.jsp页面
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>Struts 2.x</title>
</head>
<body>
<h1><s:property value="department.did"/></h1>
<h1><s:property value="department.dname"/></h1>
<h1><s:property value="department.dlocation"/></h1>
</body>
</html>
这个时候所有的标签不需要做任何直接性的处理就可以找到跳转过来的Action本身所具备的内容。
但是在编写代码的过程之中,Struts 2.x这种将JSP与Action紧密连接的形式我们并不会习惯,因为大部分人都习惯于利用request属性传递操作。
范例:利用request属性传递
@Override
public String execute() throws Exception {
this.department.setDid(1001L);
this.department.setDname("设计部");
this.department.setDlocation("米兰");
ServletActionContext.getRequest().setAttribute("department", department);
return "department.show";
}
此时的标签无法找到属性范围中的内容,那么如果要想在Struts 2.x的标签里面访问属性范围中的内容则在访问前请加上#范围名称
,例如#request
表示request属性范围。
范例:修改标签