java struts2入门学习--OGNL语言基本用法(一)

2014-11-24 02:35:58 · 作者: · 浏览: 0
一.知识点学习
1.struts2中包含以下6种对象,requestMap,sessionMap,applicationMap,paramtersMap,attr,valueStack;
1)requestMap用来存放包含当前HttpServletRequest的属性(attribute)的Map,简单来说就是request域中的值;
2)sessionMap用来存放包含当前HttpSession的属性(attribute)的Map
3)applicationMap用来存放包含当前应用的ServletContext的属性(attribute)的Map
4)paramtersMap包含当前HTTP请求参数的Map
5)attr,只是用来取值,用于按request > session > application顺序访问其属性(attribute)
6)valueStack值栈是Action的数据中心,关于Action中的所有Value都是存放在valueStack中.
2.OGNL几种常见的符号用法
会在以下几个域对象中依次查询
[pageContext对象]===>requestMap对象===>valueStack对象===>sessionMap对象===>applicationMap对象===>空白字符串
注意:pageContext对象不是Struts2的数据中心之一.
3.#用法:
1) 作用于struts2的域对象,而不是普通域对象
2)作用于JavaBean对象
3)<===>作用于普通字符串
二.实例
1.源码
OgnlAction.java
复制代码
package ognl;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class OgnlAction extends ActionSupport {
private static final long serialVersionUID = -842453764814706964L;
public String execute() throws Exception {
// 放置在requestMap对象中 1
ServletActionContext.getRequest().setAttribute("username", "request_username");
// 放置在SessionMap对象中3
ActionContext.getContext().getSession().put("username", "session_username");
// 放置在ApplicationMap对象中
ServletActionContext.getServletContext().setAttribute("username", "application_username");
//放置在ValueStack对象中2
ActionContext.getContext().getValueStack().set("username", "valuestack_username");;
return SUCCESS;
}
}
复制代码
User.java
复制代码
package ognl;
/**
* @ClassName: User
* @Description: 用户
* @author: amosli
* @email:amosli@infomorrow.com
* @date Feb 17, 2014 11:00:11 PM
*/
//JavaBean对象
public class User {
private Integer id;// 编号
private String name;// 姓名
private Integer age;// 年龄
public User() {
}
public User(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
复制代码
struts.xml
复制代码
< xml version="1.0" encoding="UTF-8" >
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
复制代码
ognl_struts.xml
复制代码
< xml version="1.0" encoding="UTF-8" >
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
/WEB-INF/ognl_success. jsp
复制代码
ognl_2.jsp
复制代码
<%@ page language="java" contentType="text/ html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page import="java.util.*" %>
<%@ page import="ognl.User" %>