效果如下图:
ognl.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>title</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<!-- Ognl标签使用 -->
<%--映射栈:带# --%>
<s:property value="#name"/><br/>
<s:property value="#request.name"/><br/>
<s:property value="#session.name"/><br/>
<s:property value="#application.name"/><br/>
<s:property value="#parameters"/><br/> <%--参数 --%>
<s:property value="#attr.request.name"/><br/> <%--attribute将request、session和application封装起来 --%>
<s:property value="#attr.session.name"/><br/>
<s:property value="#attr.application.name"/><br/>
<%--ognl算法 --%>
<s:property value="30+20"/><br/>
<s:property value="true&&true"/><br/>
<s:property value="true&&false"/><br/>
<s:property value="true||false"/><br/>
<s:property value="false||false"/><br/>
<s:property value="!false"/><br/>
<s:property value="false?'真的':'假的'"/><br/>
<%--创建数组或集合 --%>
<s:property value="{'小火','傻鸟','小黑','十品'}"/><br/>
<%--集合 --%>
<s:property value="#{'1':'小火','2':'傻鸟','3':'小黑','4':'十品'}"/>
<s:debug></s:debug>
</body>
</html>
ognlDemo.java
package star.july.ognl;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class OgnlDemo extends ActionSupport{
Student student;
public void setStudent(Student student) {
this.student = student;
}
public String set(){
student.setName("陈二狗");
ActionContext ac = ActionContext.getContext();
//自己放值
ac.put("name", student);
Map rp = (Map) ac.get("request");
rp.put("name", student);
Map<String, Object> session = ac.getSession();
session.put("name", student);
Map<String, Object> application = ac.getApplication();
application.put("name", student);
Map<String, Object> parameters = ac.getParameters();
parameters.put("name", student);
System.out.println(student);
return SUCCESS;
}
}
实体类,Student.java
package star.july.ognl;
public class Student {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + "]";
}
}
xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="student" namespace="/" extends="struts-default">
<action name="student" class="star.july.ognl.OgnlDemo" method="set">
<result name="success">/ognl.jsp</result>
</action>
</package>
</struts>