Java mac idea Struts2的使用03

1. OGNL表达式

1.1 什么是OGNL表达式

OGNL:对象视图导航语言

使用OGNL表达式,需要两个前提

  1. 需要一个Root,这里用一个User对象来做Root
  2. 需要一个context(Map)

User对象

public class User {
    private String name;
    private Integer age;
    
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    
    public User(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + "]";
    }
    
    
}

准别一个回音方法

public class echoUtils {
    
    //回音方法
        public static Object echo(Object o){
            return o;
        }
}
//展示OGNL语法
public class Demo {
    @Test
    //准备工作
    public void fun1() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        //将rootUser作为root部分
        oc.setRoot(rootUser);
        //将context这个Map作为Context部分
        oc.setValues(context);
        //书写OGNL
        Ognl.getValue("", oc, oc.getRoot());
    }
    
    @Test
    //基本语法演示
    //取出root中的属性值
    public void fun2() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        oc.setRoot(rootUser);
        oc.setValues(context);
        //书写OGNL
        
        //取出root中user对象的name属性
        String name = (String) Ognl.getValue("name", oc, oc.getRoot());
        Integer age = (Integer) Ognl.getValue("age", oc, oc.getRoot());
        System.out.println(name);
        System.out.println(age);
    }
    @Test
    //基本语法演示
    //取出context中的属性值
    public void fun3() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        oc.setRoot(rootUser);
        oc.setValues(context);
        //书写OGNL
        
        //取出context中键为user1对象的name属性
        String name = (String) Ognl.getValue("#user1.name", oc, oc.getRoot());
        String name2 = (String) Ognl.getValue("#user2.name", oc, oc.getRoot());
        Integer age = (Integer) Ognl.getValue("#user2.age", oc, oc.getRoot());
        System.out.println(name);
        System.out.println(name2);
        System.out.println(age);
    }
    
    @Test
    //基本语法演示
    //为属性赋值
    public void fun4() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        oc.setRoot(rootUser);
        oc.setValues(context);
        //书写OGNL
        
        //将root中的user对象的name属性赋值
        Ognl.getValue("name='jerry'", oc, oc.getRoot());
        String name = (String) Ognl.getValue("name", oc, oc.getRoot());
        
        String name2 = (String) Ognl.getValue("#user1.name='冬冬',#user1.name", oc, oc.getRoot());
        System.out.println(name);
        System.out.println(name2);
    }
    
    @Test
    //基本语法演示
    //调用方法
    public void fun5() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        oc.setRoot(rootUser);
        oc.setValues(context);
        //书写OGNL
        
        //调用root中user对象的setName方法
        Ognl.getValue("setName('lilei')", oc, oc.getRoot());
        String name = (String) Ognl.getValue("getName()", oc, oc.getRoot());
        
        String name2 = (String) Ognl.getValue("#user1.setName('lucy'),#user1.getName()", oc, oc.getRoot());
        
        
        System.out.println(name);
        System.out.println(name2);
    }
    
    
    @Test
    //基本语法演示
    //调用静态方法
    public void fun6() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        oc.setRoot(rootUser);
        oc.setValues(context);
        //书写OGNL
        
        String name = (String) Ognl.getValue("@a_ognl.EchoUtils@echo('hello 冬冬!')", oc, oc.getRoot());
        //Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc, oc.getRoot());
        Double pi = (Double) Ognl.getValue("@@PI", oc, oc.getRoot());
        System.out.println(name);
        System.out.println(pi);
    }   
    
    @Test
    //基本语法演示
    //ognl创建对象-list|map
    public void fun7() throws Exception{
        //准备ONGLContext
            //准备Root
            User rootUser = new User("tom",18);
            //准备Context
            Map<String,User> context = new HashMap<String,User>();
            context.put("user1", new User("jack",18));
            context.put("user2", new User("rose",22));
        OgnlContext oc = new OgnlContext();
        oc.setRoot(rootUser);
        oc.setValues(context);
        //书写OGNL
        
        //创建list对象
        Integer size = (Integer) Ognl.getValue("{'tom','jerry','jack','rose'}.size()", oc, oc.getRoot());
        String name = (String) Ognl.getValue("{'tom','jerry','jack','rose'}[0]", oc, oc.getRoot());
        String name2 = (String) Ognl.getValue("{'tom','jerry','jack','rose'}.get(1)", oc, oc.getRoot());
    
        /*System.out.println(size);
        System.out.println(name);
        System.out.println(name2);*/
        //创建Map对象
        Integer size2 = (Integer) Ognl.getValue("#{'name':'tom','age':18}.size()", oc, oc.getRoot());
        String name3  = (String) Ognl.getValue("#{'name':'tom','age':18}['name']", oc, oc.getRoot());
        Integer age  = (Integer) Ognl.getValue("#{'name':'tom','age':18}.get('age')", oc, oc.getRoot());
        System.out.println(size2);
        System.out.println(name3);
        System.out.println(age);
    }   

}

2. ognl表达式与Struts2框架结合原理

2.1 Struts2使用ognl

  1. 需要一个Root,将Action对象放入,当获取从jsp中提交的表单参数的时候,是将user对象压栈,这样user在栈顶,ognl表达式默认会操作栈顶对象
  2. 需要一个context(Map),将valueStack放入

2.2 栈

  1. 栈的特性
    先进后出

  2. 栈必须具备的两个方法
    这里栈是由ArrayList模拟的

public Object pop() {
        return this.remove(0);
    }

    public void push(Object o) {
        this.add(0, o);
    }

2.3 参数赋值原理

form.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/Demo2Action">
        用户名:<input type="text" name="name" /><br>
        <input type="submit" value="提交" />
    </form>
    
</body>
</html>
public class Demo2Action extends ActionSupport implements ModelDriven<User> {
    
    private User u = new User();
    
    @Override
    public String execute() throws Exception {
        
        
        
        System.out.println(u);
        
        
        return SUCCESS;
    }

    // Preparable接口的方法,用来提前将user对象压栈
    /*@Override
    public void prepare() throws Exception {
                //压入栈顶
                //1获得值栈
                ValueStack vs = ActionContext.getContext().getValueStack();
                //2将u压入栈顶
                vs.push(u);
    }*/

    @Override
    public User getModel() {
        return u;
    }
}

Struts2中的filter执行顺序,modelDriven和prepare的作用是一样的,只是不需要自己压栈了,只需要返回user对象

<interceptor-stack name="paramsPrepareParamsStack">
                <interceptor-ref name="exception"/>
                <interceptor-ref name="alias"/>
                <interceptor-ref name="i18n"/>
                <interceptor-ref name="checkbox"/>
                <interceptor-ref name="datetime"/>
                <interceptor-ref name="multiselect"/>
                <interceptor-ref name="params"/>
                <interceptor-ref name="servletConfig"/>
                <interceptor-ref name="prepare"/>
                <interceptor-ref name="chain"/>
                <interceptor-ref name="modelDriven"/>
                <interceptor-ref name="fileUpload"/>
                <interceptor-ref name="staticParams"/>
                <interceptor-ref name="actionMappingParams"/>
                <interceptor-ref name="params"/>
                <interceptor-ref name="conversionError"/>
                <interceptor-ref name="validation">
                    <param name="excludeMethods">input,back,cancel,browse</param>
                </interceptor-ref>
                <interceptor-ref name="workflow">
                    <param name="excludeMethods">input,back,cancel,browse</param>
                </interceptor-ref>
            </interceptor-stack>

2.4 配置文件中使用ognl表达式

<action name="Demo3Action" class="config.Demo3Action" method="execute" >
            <result name="success" type="redirectAction" >
                <param name="actionName">Demo1Action</param>
                <param name="namespace">/</param>
                <!-- 如果添加的参数struts"看不懂".就会作为参数附加重定向的路径之后.
                     如果参数是动态的.可以使用${}包裹ognl表达式.动态取值
                 -->
                <param name="name">${name}</param>
            </result>
        </action>
public class Demo3Action extends ActionSupport {
    
    private String  name;
    
    @Override
    public String execute() throws Exception {
        name = "jerry";//从数据库中查询
        return SUCCESS;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3. jsp页面使用ognl表达式

  1. 客户列表的Action使用ActionContext进行参数获取和参数放置
public String list() throws Exception {

        ActionContext.getContext().getValueStack();

        // 1. 接受参数
//        String cust_name = ServletActionContext.getRequest().getParameter("cust_name");

        String cust_name = (String) ActionContext.getContext().getParameters().get("cust_name");

        // 2. 创建离线查询对象
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);

        // 3. 根据参数封装查询条件
        if (StringUtils.isNotBlank(cust_name)) {

            detachedCriteria.add(Restrictions.like("cust_name", "%" + cust_name + "%"));

        }

        List list = customerService.getAll(detachedCriteria);

//        ServletActionContext.getRequest().setAttribute("list", list);

        ActionContext.getContext().put("list", list);

        return "list";
    }
  1. jsp页面使用ognl来获取服务器发送的数据
引入标签库
<%@ taglib  prefix="s" uri="/struts-tags" %>

方式一:
<s:iterator value="#list" var="cust" >
    <TR
            style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
        <TD>
            <s:property value="#cust.cust_name" />
        </TD>
        <TD>
            <s:property value="#cust.cust_level" />
        </TD>
        <TD>
            <s:property value="#cust.cust_source" />
        </TD>
        <TD>
            <s:property value="#cust.cust_linkman" />
        </TD>
        <TD>
            <s:property value="#cust.cust_phone" />
        </TD>
        <TD>
            <s:property value="#cust.cust_mobile" />
        </TD>
        <TD>
            <a href="${pageContext.request.contextPath }/customerServlet?method=edit&custId=${customer.cust_id}">修改</a>
            &nbsp;&nbsp;
            <a href="${pageContext.request.contextPath }/customerServlet?method=delete&custId=${customer.cust_id}">删除</a>
        </TD>
    </TR>
</s:iterator>


方式二:

<s:iterator value="#list"  >
    <TR         
        style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
            <TD>
                <s:property value="cust_name" />
                          </TD>
                                            
            <TD>
                <s:property value="cust_level" />
            </TD>
            <TD>
                <s:property value="cust_source" />
            </TD>
            <TD>
                <s:property value="cust_linkman" />
            </TD>
            <TD>
                <s:property value="cust_phone" />
            </TD>
            <TD>
                <s:property value="cust_mobile" />
            </TD>
            <TD>
                <a href="${pageContext.request.contextPath }/customerServlet?method=edit&custId=${customer.cust_id}">修改</a>
                &nbsp;&nbsp;
                <a href="${pageContext.request.contextPath }/customerServlet?method=delete&custId=${customer.cust_id}">删除</a>
            </TD>
    </TR>
</s:iterator>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,884评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,212评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,351评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,412评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,438评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,127评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,714评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,636评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,173评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,264评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,402评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,073评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,763评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,253评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,382评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,749评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,403评论 2 358

推荐阅读更多精彩内容

  • 概述 什么是Struts2的框架Struts2是Struts1的下一代产品,是在 struts1和WebWork的...
    inke阅读 2,263评论 0 50
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,656评论 18 399
  • 1、什么是框架? 框架就是一组程序的集合,本质上是一组jar包的集合,jar包中存有class文件或一些资源文件。...
    Yulin_ZH阅读 972评论 1 1
  • 正如 这偶尔的饥馁 水 蒸发于无形 从肉体中渐渐抽出 你看见自己 远处 塔照见在泥潭 伞 映出风雨 青黄一片的 你...
    四夕山人阅读 244评论 0 1
  • 人的相处,很多时候讲求的是就是一种感觉:舒服。 因为感觉舒服,才愿意和对方继续相处下去。 这样的例子,生活中随处可...
    菁草阅读 267评论 -1 1