package cn.itcast.ognl;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlDemo1 {
public static void main(String[] args) throws OgnlException {
// ognl可以通过对象调用方法
// System.out.println("aaa".length());
// 使用ognl来完成上面操作
// 1.创建一个ognl上下文
OgnlContext context = new OgnlContext();
Object obj1 = Ognl.getValue("'aaa'.length()", context.getRoot());
System.out.println(obj1);
}
}
package cn.itcast.ognl;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlDemo2 {
public static void main(String[] args) throws OgnlException {
// ognl可以通过类调用静态方法
System.out.println(Math.max(10, 20));
System.out.println(Math.PI);
// 使用ognl来完成上面操作
// 1.创建一个ognl上下文
OgnlContext context = new OgnlContext();
Object obj1 = Ognl.getValue("@java.lang.Math@max(10,20)",
context.getRoot());
System.out.println(obj1);
Object obj2 = Ognl.getValue("@java.lang.Math@PI", context.getRoot());
System.out.println(obj2);
}
}
package cn.itcast.ognl;
public class Person {
private String name;
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
package cn.itcast.ognl;
public class Dog {
private String name;
private Person p;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getP() {
return p;
}
public void setP(Person p) {
this.p = p;
}
}
package cn.itcast.ognl;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlDemo3 {
public static void main(String[] args) throws OgnlException {
// 创建一个ognl上下文
OgnlContext context = new OgnlContext();// 本质上是一个Map集合
Person p = new Person();
p.setName("张三");
Dog dog = new Dog();
dog.setName("lucy");
p.setDog(dog); // 张三有条狗叫lucy
context.setRoot(p);
Dog dog1 = new Dog();
dog1.setName("豆豆");
Person pp = new Person();
pp.setName("jams");
dog1.setP(pp);
context.put("dog", dog1);
context.put("name", "tom");
// 使用ognl来获取根中数据,不需要加#
Object name1 = Ognl.getValue("name", context, context.getRoot());
System.out.println(name1);
// 使用ognl来获取非根中的数据,获取非根中的数据 需要使用#
Object name2 = Ognl.getValue("#name", context, context.getRoot());
System.out.println(name2);
// 获取张三的狗的名称
Object name3 = Ognl.getValue("dog.name", context, context.getRoot());
System.out.println(name3);
// 获取豆豆的主人名称
Object name4 = Ognl.getValue("#dog.p.name", context, context.getRoot());
System.out.println(name4);
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>演示:使用ognl来通过对象调用方法</title>
</head>
<body>
<s:property value="'abc'.length()" />
<hr>
<s:property value="@java.lang.Math@max(10,20)" />
</body>
</html>
Struts会把下面这些映射压入ContextMap中
package cn.test.domain; public class Product { private String name; private double price; private int count; public String getName() { return name; } public Product() { super(); } public Product(String name, double price, int count) { super(); this.name = name; this.price = price; this.count = count; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
package cn.test.domain; public class User { public User() { super(); } public User(String username, String password, int age, String sex) { super(); this.username = username; this.password = password; this.age = age; this.sex = sex; } private String username; private String password; private int age; private String sex; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }struts.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> <constant name="struts.ognl.allowStaticMethodAccess" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="ognlDemo1" class="cn.test.action.OgnlDemo1Action"></action> <action name="ognlDemo2" class="cn.test.action.OgnlDemo2Action"> <result>/ognl2.jsp</result> </action> <action name="ognlDemo3" class="cn.test.action.OgnlDemo3Action"> <result>/ognl3.jsp</result> </action> <action name="ognlDemo4" class="cn.test.action.OgnlDemo4Action"> <result>/ognl4.jsp</result> </action> <action name="ognlDemo5" class="cn.test.action.OgnlDemo5Action"> <result>/ognl5.jsp</result> </action> <action name="ognlDemo6" class="cn.test.action.OgnlDemo6Action"> <result>/ognl6.jsp</result> </action> </package> </struts>my.properties
package cn.test.action; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo1Action extends ActionSupport { @Override public String execute() throws Exception { // 获取ValueStack // 1.通过request获取 ValueStack vs = (ValueStack) ServletActionContext.getRequest() .getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY); System.out.println(vs); // 2.通过ActionContext获取 ValueStack vs2 = ActionContext.getContext().getValueStack(); System.out.println(vs2); return null; } }
package cn.test.action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo2Action extends ActionSupport { @Override public String execute() throws Exception { // 向valueStack中存入数据 ValueStack vs=ActionContext.getContext().getValueStack(); vs.set("username", "tom"); vs.push("hello world"); return SUCCESS; } }ognl2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:使用ognl来获取valueStack数据</title> </head> <body> 1.获取栈顶的map <br> <s:property value="username" /> <hr> 2.获得栈顶非Map集合数据 <br> <s:property value="[1].top" /> <hr> 3.获得OgnlContext中数据 <br> <% request.setAttribute("rname", "rvalue"); session.setAttribute("sname", "svalue"); application.setAttribute("aname", "avalue"); %> <s:property value="#request.rname" /> <br> <s:property value="#session.sname" /> <br> <s:property value="#application.aname" /> <br> <s:property value="#attr.sname" /><br> <s:property value="#parameters.username[0]" /> <s:debug /> </body> </html>
package cn.test.action; import java.util.ArrayList; import java.util.List; import cn.test.domain.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo3Action extends ActionSupport { @Override public String execute() throws Exception { // 向valueStack中存入数据(root) ValueStack vs = ActionContext.getContext().getValueStack(); List<User> users = new ArrayList<User>(); users.add(new User("tom", "123", 20, "男")); users.add(new User("jams", "456", 21, "男")); users.add(new User("fox", "789", 26, "男")); // vs.push(users); vs.set("users", users); return SUCCESS; } }ognl3.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:使用ognl来获取valueStack中复杂数据</title> </head> <body> 1.使用push存储数据存取 <br> <s:property value="[0].top.users" /> <br> <s:iterator value="[0].top.users" var="user"> username:<s:property value="#user.username" /> <br> password:<s:property value="#user.password" /> <hr> </s:iterator> <hr> <s:iterator value="[0].top.users"> username:<s:property value="username" /> <br> password:<s:property value="password" /> <hr> </s:iterator> <hr> 2.使用set存储数据 <hr> <s:property value="users" /> <br> <s:iterator value="users" var="user"> username:<s:property value="#user.username" /> <br> password:<s:property value="#user.password" /> <hr> </s:iterator> <hr> <s:iterator value="users"> username:<s:property value="username" /> <br> password:<s:property value="password" /> <hr> </s:iterator> <s:debug /> </body> </html>
package cn.test.action; import java.util.ArrayList; import java.util.List; import cn.test.domain.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo4Action extends ActionSupport implements ModelDriven<User> { private List<User> users; private User user = new User("tom", "123", 20, "男"); public User getModel() { return user; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public String getHello() { return "hello world"; } @Override public String execute() throws Exception { ValueStack vs = ActionContext.getContext().getValueStack(); users = new ArrayList<User>(); users.add(new User("tom", "123", 20, "男")); users.add(new User("jams", "456", 21, "男")); users.add(new User("fox", "789", 26, "男")); user = new User("fox", "789", 26, "男"); return SUCCESS; } }ognl4.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:使用ognl来获取valueStack中复杂数据</title> </head> <body> <s:property value="hello" /> <hr> <s:property value="username" /> <s:property value="age" /> <hr> <s:property value="model.username"/> <s:property value="model.age"/> <hr> <s:iterator value="users" var="u"> <s:property value="#u.username" /> <br> </s:iterator> <s:debug /> </body> </html>
package cn.test.action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo5Action extends ActionSupport { @Override public String execute() throws Exception { ValueStack vs = ActionContext.getContext().getValueStack(); vs.set("username", "张三"); // 向ValueStack压入数据 return SUCCESS; } }ognl5.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:使用el获取ValueStack中数据</title> </head> <body> Ognl获取:<s:property value="username"/><br> el获取:${username } <s:debug /> </body> </html>
package cn.test.action; import java.util.ArrayList; import java.util.List; import cn.test.domain.Product; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo6Action extends ActionSupport { private List<Product> ps; public List<Product> getPs() { return ps; } public void setPs(List<Product> ps) { this.ps = ps; } @Override public String execute() throws Exception { // 对ps进行赋值 ps = new ArrayList<Product>(); ps.add(new Product("电视机", 1800, 100)); ps.add(new Product("洗衣机", 800, 10)); ps.add(new Product("空调", 3800, 100)); return SUCCESS; } }ognl6.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:进行投影操作</title> </head> <body> <s:property value="ps" /> <br>1.使用iterator进行遍历 <br> <s:iterator value="ps" var="p"> 名称:<s:property value="#p.name" /> <br> 价格:<s:property value="#p.price" /> <br> 数量:<s:property value="#p.count" /> <br> <hr> </s:iterator> <hr> 2.对集合进行投影,只得到指定的属性 <br> <s:iterator value="ps.{name}" var="pname"> <s:property value="#pname" /> </s:iterator> <hr> 3.将ps中价格大于1000的商品得到 <br> <s:iterator value="ps.{?#this.price>1000}" var="p"> 名称:<s:property value="#p.name" /> <br> 价格:<s:property value="#p.price" /> <br> 数量:<s:property value="#p.count" /> <br> </s:iterator> <hr> 4.将ps中价格大于1000的商品名称得到 <br> <s:iterator value="ps.{?#this.price>1000}.{name}" var="pname"> <s:property value="#pname" /> <br> <hr> </s:iterator> <s:debug /> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:进行投影操作</title> </head> <body> 1.可以使用#来构建一个Map集合 <br> <s:iterator value="#{'name':'tom','age':20}" var="entry"> <s:property value="#entry.key" />----<s:property value="#entry.value" /> <br> </s:iterator> <hr> 2.可以构建List集合 <br> <s:iterator value="{'aa','bb','cc'}" var="v"> <s:property value="#v" /> </s:iterator> <hr> 3.手动创建一个集合,在Struts2中是结合表单标签使用的 <br> <s:form> <s:radio list="{'男','女'}" name="sex"></s:radio> <s:radio list="#{'男':'male','女':'female'}" name="sex"></s:radio> <s:select list="{'a','b','c'}" name="aa"></s:select> <s:select list="#{'a':'aaa','b':'bbb','c':'ccc' }" name="aa"></s:select> </s:form> <s:debug /> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:%号的使用</title> </head> <body> <% request.setAttribute("username", "tom"); %> <s:property value="#request.username" default="hello" /> <br> <s:property value="%{#request.username}" /> <br> <s:property value="%{'#request.username'}" /> <br> <hr> <s:textfield name="abc" value="%{#request.username}" /> <s:debug /> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示:$用法</title> </head> <body> <% request.setAttribute("username", "张三"); %> 在国际化文件中使用: <br> <s:i18n name="cn.test.resource.my"> <s:text name="username" /> </s:i18n> <s:debug /> </body> </html>
<!-- 在默认栈中增加token拦截器 --> <interceptors> <interceptor-stack name="tokenStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="token"> <!-- 配置token拦截器拦截哪些方法 --> <param name="includeMethods">save</param> </interceptor-ref> </interceptor-stack> </interceptors>
package cn.itcast.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegistServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); String token = request.getParameter("token"); String _token = (String) request.getSession().getAttribute("token"); request.getSession().removeAttribute("token"); if (token.equals(_token)) { System.out.println("将" + username + " 与" + password + "存储到数据库中,完成注册"); } else { response.getWriter().write("不允许表单重复提交"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <% //生成一个令牌 String token=UUID.randomUUID().toString(); session.setAttribute("token", token); %> <form action="${pageContext.request.contextPath}/regist" method="get"> <input type="hidden" name="token" value="<%=token%>"> username:<input type="text" name="username"><br> password:<input type="password" name="password"><br> <input type="submit" value="注册"> </form> </body> </html>
<?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="default" namespace="/" extends="struts-default"> <action name="regist" class="cn.itcast.action.RegistAction"> <result name="invalid.token">/token.jsp</result> <interceptor-ref name="token" /> <interceptor-ref name="defaultStack" /> </action> </package> </struts>RegistAction
package cn.itcast.action; import com.opensymphony.xwork2.ActionSupport; public class RegistAction extends ActionSupport { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String execute() throws Exception { System.out.println("将" + username + " 与" + password + "存储到数据库中,完成注册"); return null; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <form action="${pageContext.request.contextPath}/regist.action" method="get"> <s:token/> username:<input type="text" name="username"><br> password:<input type="password" name="password"><br> <input type="submit" value="注册"> </form> </body> </html>token.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <s:actionerror/> </body> </html>
package cn.test.domain; import org.apache.struts2.json.annotations.JSON; public class Product { private int id; private String name; private double price; private int count; public Product() { super(); } public Product(int id, String name, double price, int count) { super(); this.id = id; this.name = name; this.price = price; this.count = count; } // @JSON(serialize=false) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }Ajax1Action
package cn.test.action; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class Ajax1Action extends ActionSupport { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String execute() throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); response.getWriter().write("hello " + msg); response.getWriter().close(); return null; } }Ajax2Action
package cn.test.action; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import cn.test.domain.Product; import com.opensymphony.xwork2.ActionSupport; public class Ajax2Action extends ActionSupport { private List<Product> ps; private Product p; public Product getP() { return p; } public void setP(Product p) { this.p = p; } public List<Product> getPs() { return ps; } public void setPs(List<Product> ps) { this.ps = ps; } @Override public String execute() throws Exception { ps = new ArrayList<Product>(); ps.add(new Product(1, "洗衣机", 1800, 10)); ps.add(new Product(2, "电视机", 2800, 20)); ps.add(new Product(3, "缝纫机", 800, 50)); p = new Product(3, "缝纫机", 800, 50); return SUCCESS; } }my.js
function getXmlHttpRequest() { var xmlhttp=null; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); //针对于现在的浏览器包括IE7以上的版本 } else if(window.ActiveXObject){ // 针对于IE5,IE6版本 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; }struts.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="default" namespace="/" extends="json-default"> <action name="ajax1" class="cn.test.action.Ajax1Action"></action> <action name="ajax2" class="cn.test.action.Ajax2Action"> <result type="json"> <param name="includeProperties">ps\[\d+\]\.name,ps\[d+\]\.price,ps\[\d+\]\.count</param> </result> </action> </package> </struts>ajax1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>第一种Struts2处理异步请求</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> function hello() { //1.得到XMLHttpRequest对象 var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { if (xmlhttp.status == 200 && xmlhttp.readyState == 4) { alert(xmlhttp.responseText); } }; //3.open xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax1?msg=" + document.getElementById("t").value); //4.send xmlhttp.send(null); } </script> </head> <body> <input type="text" id="t"> <input type="button" value="提交" onclick="hello();"> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>第一种Struts2处理异步请求</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> function showProduct() { //1.得到XMLHttpRequest对象 var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { if (xmlhttp.status == 200 && xmlhttp.readyState == 4) { alert(xmlhttp.responseText); // var jsonObj = eval("(" + xmlhttp.responseText + ")"); } }; //3.open xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax2?msg=" + document.getElementById("t").value); //4.send xmlhttp.send(null); } </script> </head> <body> <input type="text" id="t"> <input type="button" value="提交" onclick="showProduct();"> </body> </html>