struts2 Ognl用法(Ognl类的用法)

首选,熟悉Ognl类的用法

1.定义两个JavaBean,User和Departments

package com.struts2.bean;

public class User {

 private String username;

 private int age;

 private Department depart=new Department();

 public String getUsername() {

  return username;

 }

 public void setUsername(String username) {

  this.username = username;

 }

 public int getAge() {

  return age;

 }

 public void setAge(int age) {

  this.age = age;

 }

 public Department getDepart() {

  return depart;

 }

 public void setDepart(Department depart) {

  this.depart = depart;

 }

}

package com.struts2.bean;

public class Department {

 private int departCode;

 private String departname;

 public int getDepartCode() {

  return departCode;

 }

 public void setDepartCode(int departCode) {

  this.departCode = departCode;

 }

 public String getDepartname() {

  return departname;

 }

 public void setDepartname(String departname) {

  this.departname = departname;

 }

 

}

2.用Ognl类访问,赋值(需要ognl-2.6.11.jar)

package com.test.main;

import java.util.HashMap;

import java.util.Map;

import ognl.Ognl;

import ognl.OgnlException;

import com.struts2.bean.*;

public class TestMain {

 /**

  * @param args

  * @throws OgnlException 

  */

 public static void main(String[] args) throws OgnlException {

  // TODO Auto-generated method stub

  TestMain test=new TestMain();

  test.getValueByOgnl();

  test.setValueByOgnl();

 }

 

 private void getValueByOgnl() throws OgnlException

 {

  User user=new User();

  user.setUsername("张三");

  user.setAge(25);

  

  Map<String,String> map=new HashMap<String,String>();

  map.put("name""李四");

  

  //当指定根对象时,不能加#,否则获取为null

  System.out.println("姓名:"+Ognl.getValue(Ognl.parseExpression("username"), user)+

    " 年龄:"+Ognl.getValue(Ognl.parseExpression("Age"), user));

  

  //当指定上下文,并且表达式属性不在根对象中时,必须指定#,否则产生NoSuchPropertyException异常

  System.out.println("Map's name:"+Ognl.getValue(Ognl.parseExpression("#name"), map,user));

    

  

  

  

 }

 

 private void setValueByOgnl() throws OgnlException

 {

  User user=new User();

  user.setUsername("张三");

  user.setAge(25);

  

  Ognl.setValue("depart.departname", user, "生产部");

  

  //当指定根对象后,

  System.out.println("姓名:"+Ognl.getValue(Ognl.parseExpression("username"), user)+

    " 年龄:"+Ognl.getValue(Ognl.parseExpression("Age"), user)+

    " 部门:"+Ognl.getValue(Ognl.parseExpression("depart.departname"), user));

  

  

  

  

 }

}

发布了36 篇原创文章 · 获赞 3 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章