首页 > 代码库 > OGNL访问复杂对象和静态方法

OGNL访问复杂对象和静态方法

今天学习了Struts的OGNL访问复杂对象和静态方法,现在来总结下。

1、OGNL访问复杂对象

  (1)先创建包model、action、在model中创建模型Student(name,age)。action中创建HelloAction

    

package com.fangchao.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fangchao.model.Student;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Student student;
    
    private List<Student> students;
    
    private Map<String,Student> studentMap;
    
    
    public Student getStudent() {
        return student;
    }


    public void setStudent(Student student) {
        this.student = student;
    }


    public List<Student> getStudents() {
        return students;
    }


    public void setStudents(List<Student> students) {
        this.students = students;
    }


    public Map<String, Student> getStudentMap() {
        return studentMap;
    }


    public void setStudentMap(Map<String, Student> studentMap) {
        this.studentMap = studentMap;
    }


    public static long getSerialversionuid() {
        return serialVersionUID;
    }


    @Override
    public String execute() throws Exception {
        
        ActionContext actonContext=ActionContext.getContext();
        
        student=new Student("fangchao", 23);
        
        students=new ArrayList<Student>();
        students.add(new Student("fangchao1",21));
        students.add(new Student("fangchao2",22));
        
        studentMap=new HashMap<String,Student>();
        studentMap.put("good", new Student("fangchao3", 23));
        studentMap.put("bad", new Student("fangchao4", 24));
        return SUCCESS;
        
    }
    
    

}

  前台页面success.jsp(注意在页面上加入<%@taglib prefix="s" uri="/struts-tags" %>)

  

ognl访问javabean对象:
<s:property value="student.name"/>
<s:property value="student.age"/><br>

ognl访问List对象:
<s:property value="students[0].name"/>
<s:property value="students[0].age"/><br>
<s:property value="students[1].name"/>
<s:property value="students[1].age"/><br>

ognl访问Map:
<s:property value="studentMap[‘good‘].name"/>
<s:property value="studentMap[‘good‘].age"/><br>
<s:property value="studentMap[‘bad‘].name"/>
<s:property value="studentMap[‘bad‘].age"/><br>

 

2、OGNL访问静态方法

  访问静态方法基本同上。除了在struts.xml中加入(<constant name="struts.ognl.allowStaticMethodAccess" value="http://www.mamicode.com/true"></constant> )表示可以访问静态方法。

  代码如下:

<body>
    访问静态属性:<s:property value="@com.fangchao.common.MyStatic@str"/>
    访问静态方法:<s:property value="@com.fangchao.common.MyStatic@print()"/>
</body>

  唯一需要注意的地方是访问时需要加上@符号,同时需要完整的路径访问。

 

OGNL访问复杂对象和静态方法