使用 OGNL 通过 Action 获取请求参数

OGNL:Object-Graph Navigation Language,对象图导航语言 ,可以方便地操作对象属性的开源表达式语言

至于怎么说是表达式语言,看了书上的例子大概了解了一点。

1. OnglAction.java

 1 package com.lihui;
2
3 import javax.servlet.http.HttpServletRequest;
4
5 import org.apache.struts2.ServletActionContext;
6
7 import com.opensymphony.xwork2.ActionContext;
8 import com.opensymphony.xwork2.ActionSupport;
9
10 public class OnglAction extends ActionSupport{
11
12 private Car myCar;
13
14 @Override
15 public String execute() throws Exception {
16 //获取ActionContext 示例,以便访问 servlet API
17 ActionContext ctx = ActionContext.getContext();
18 ctx.getApplication().put("msg", "application信息");
19 ctx.getSession().put("msg", "session信息");
20 HttpServletRequest request = ServletActionContext.getRequest();
21 request.setAttribute("msg", "request信息");
22 myCar = new Car();
23 myCar.setColor("Black");
24 myCar.setWidth("1.5cm");
25 ctx.getSession().put("mycar", myCar);
26 return SUCCESS;
27 }
28
29 public Car getCar(){
30 return myCar;
31 }
32
33 public void setCar(Car car){
34 this.myCar = car;
35 }
36
37 }

2.自定义Car类

 1 package com.lihui;
2
3 public class Car {
4 private String width;
5 private String color;
6 public String getColor(){
7 return color;
8 }
9 public void setColor(String color){
10 this.color = color;
11 }
12 public String getWidth(){
13 return width;
14 }
15 public void setWidth(String width){
16 this.width = width;
17 }
18 }

3.struts,xml

 1 <?xml version="1.0" encoding="GB2312" ?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6
7 <struts>
8 <package name="com.lihui" extends="struts-default">
9 <action name="onglAction" class="com.lihui.OnglAction">
10 <result name="success">msg.jsp</result>
11 </action>
12 </package>
13
14 </struts>

4.msg.jsp

在上面这段代码中,第16行获取值其实与第18行获取值是等价的。并且,第16行的 Car 指的应

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; utf-8"%>
2 <%@ taglib prefix="s" uri="/struts-tags" %>
3
4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
5 <html>
6 <head>
7 <title>msg.jsp</title>
8 </head>
9
10 <body>
11 <p>parameters:<s:property value="#parameters.msg"/></p>
12 <p>request.msg:<s:property value="#request.msg"/></p>
13 <p>session.msg:<s:property value="#session.msg"/></p>
14 <p>application.msg:<s:property value="#application.msg"/></p>
15 <p>attr.msg:<s:property value="#attr.msg"/></p>
16 <s:property value="Car.{?#this.color=='Black'}.{width}[0]"/><br/>
17 汽车的颜色:<s:property value="#session.mycar.color"/>
18 <p>汽车的Width为:<s:property value="#session.mycar.width"/></p>
19 <!-- 下面创建一个新集合 -->
20 <s:set name="student" value="#{'Jack':'21','Rose':'22'}"></s:set>
21 <p>学生Jack的年龄为:<s:property value="#student['Jack']"/></p>
22 </body>
23 </html>

该是类。但是测试发现,大小写并不敏感。

 

全部配置好之后,编译,启动服务器,输入 http://localhost:8080/onglAction.action?msg=lihui 后显示:

 



posted @ 2012-03-19 17:14  lihui_yy  阅读(2811)  评论(0编辑  收藏  举报