ognl.jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>OGNL</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
Ognl Page!<br/>
<ol>
<li>访问值栈中的普通属性 取出username:<s:property value="username"/></li>
<li>访问值栈中的普通属性 取出password:<s:property value="password"/></li>
<li>访问值栈中的对象的属性 取出user.Age:<s:property value="user.age"/></li>
<li>访问值栈中的对象的属性 取出cat.dog.name:<s:property value="cat.dog.name"/></li>
<li>访问值栈中的成员变量的普通方法 取出password的长度:<s:property value="password.length()"/></li>
<li>访问值栈中的对象的普通方法 取出cat.miaomiao:<s:property value="cat.miaomiao()"/></li>
<li>访问值栈中的action的普通方法 取出helloaction:<s:property value="helloaction()"/></li>
</ol>
<hr>
<ol>
<li>访问静态成员:<s:property value="@com.mytest.ognl.S@staticStr"/></li>
<li>访问静态方法:<s:property value="@com.mytest.ognl.S@StaticMethord()"/></li>
<!-- 静态方法的访问应该在配置struts.xml中配置
<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
默认的default.properties中属性值是false
-->
<li>访问Math类的方法:<s:property value="@@max(2,9)"/></li>
<!-- 访问Math类的方法时候用两个@@符号,只限于访问Math类 -->
</ol>
<hr>
<ol>
<li>访问普通类的构造方法:<s:property value="new com.mytest.ognl.User(8)"/></li>
</ol>
<hr>
<ol>
<li></li>
</ol>
<s:debug></s:debug>
</body>
</html>
User.java代码
package com.mytest.ognl;
public class User {
private int Age;
public User(){}
public User(int Age){
super();
this.Age=Age;
}
public void setAge(int age) {
Age = age;
}
public int getAge() {
return Age;
}
public String toString(){
return "user" + Age;
}
}
执行结果:
访问普通类的构造方法:那个地方的值总是取不出来?怎么回事呀?求大神帮忙给解决下。
在线等!求大神给解决
我也遇到了和楼主一样的问题,我的版本是struts-2.5.13。请问这个问题后来解决了吗?
https://stackoverflow.com/questions/31333279/ognl-fails-to-call-constructor
说是安全问题禁止这种用法了。
主要是因为struts最新的版本里面不允许在页面直接创建对象,我使用的struts-core-2.3.16.3.jar版本就可以创建。
注意:当我们在maven reponsitory仓库中下载jar包时,尽量使用下载人数较多的比较好,因为新版本可能会做一些改良。