<?xml:namespace prefix = st1 />1.1.1 业务控制器
为本示例建立一个业务控制器,该控制器用到了代码8.1中定义的Person人员信息类。该业务控制器如代码8.4所示。
代码8.4 Struts 2的OGNL示例业务控制器
| package ch8;import java.util.Date;
 import java.util.LinkedList;
 import java.util.List;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import org.apache.struts2.ServletActionContext;
 import com.opensymphony.xwork2.ActionContext;
 import com.opensymphony.xwork2.ActionSupport;
 public class OgnlAction extends ActionSupport {
 //List类型属性
 private List persons;
 //execute方法
 public String execute() throws Exception {
 // 获得ActionContext实例,以便访问Servlet API
 ActionContext ctx = ActionContext.getContext();
 // 存入application
 ctx.getApplication().put("msg", "application信息");
 // 保存session
 ctx.getSession().put("msg", "seesion信息");
 // 保存request信息
 HttpServletRequest request = ServletActionContext.getRequest();
 request.setAttribute("msg", "request信息");
 //为persons赋值
 persons = new LinkedList();
 Person person1=new Person();
 person1.setName("pla1");
 person1.setAge(26);
 person1.setBirthday(new Date());
 persons.add(person1);
 
 Person person2=new Person();
 person2.setName("pla2");
 person2.setAge(36);
 person2.setBirthday(new Date());
 persons.add(person2);
 Person person3=new Person();
 person3.setName("pla3");
 person3.setAge(16);
 person3.setBirthday(new Date());
 persons.add(person3);
 return SUCCESS;
 }
 public List getPersons() {
 return persons;
 }
 public void setPersons(List persons) {
 this.persons = persons;
 }
 }
 | 
 
该业务控制器分别在application、session和request中存入名为“msg”的字符串信息,另外定义了一个List类型属性,同时添加了两个Person类型元素。在配置文件中增加了相应的配置,代码如下:
1.1.2 JSP视图
showognl.jsp是使用了OGNL表达式的JSP视图,视图用来显示Action中处理的各种信息,读者可以看到,使用OGNL表达式,代码更加简洁和直观,如代码8.5所示。
代码8.5使用OGNL表达式的JSP视图
| http://www.w3.org/TR/ xhtml1/DTD/xhtml1-transitional.dtd">
 http://www.w3.org/1999/xhtml">
 访问OGNL上下文和Action上下文parameters:  request.msg:  session.msg:  application.msg:  attr.msg:  
 用于过滤和投影(projecting)集合 年龄大于20 1.                          - 年龄: 姓名为pla1的年龄:  
 构造Map The value of key "foo1" is  | 
 
1.1.3 运行示例
在浏览器中输入http://localhost:8080/bookcode/ch8/OgnlAction.action?msg=hello,运行结果如图8.3所示。
| 
 | 
| 图8.3 Struts 2中使用OGNL表达式 | 
 
★说明★
本示例演示了如何使用OGNL表达式来访问OGNL上下文和值栈,同时演示了如何使用OGNL表达式进行集合操作。对读者深入理解Struts 2中OGNL表达式的使用有所帮助。
	posted on 2009-08-15 17:29 
jadmin 阅读(92) 
评论(0)  编辑  收藏