0x01 环境搭建
1、创建Struts2应用
创建一个动态网站项目
2、配置Tomcat启动环境
3、在WebContent目录下的WEB-INF文件夹中创建web.xml,Tomcat启动时会加载此文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
4、将Strust2框架需要的jar包复制到WEB-INF/lib文件夹中:
5、下面建立Strust中的核心配置文件struts.xml,负责配置所有的请求对应各种类或者方法,在src目录下建立此文件,并添加以下内容:
<?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>
</struts>
6、建立一个studentAction类,内容如下:
package college;
public class studentAction {
private String name;
public String execute() throws Exception {
System.out.print("Hello Student\n");
name = "Hello Student!!!";
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
7、 默认访问Action类执行的方法是execute,success返回配置文件中标签指定的视图:
修改struts.xml配置文件,添加以下内容:
<package name="college" extends="struts-default">
<action name="Say" class="college.studentAction">
<result> /HelloWorld.jsp </result>
</action>
</package>
8、当执行college.studentAction动作时,会返回HelloWorld.jsp视图,在WebContent中创建HelloWorld.jsp,内容如下:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World</title>
</head>
<body>
${name}<br/>
Hello world !
</body>
</html>
9、启动
10、访问 http://127.0.0.1:8080/Struts2/Say.action 一个简单的Struts2应用就建立起来了
0x02 OGNL使用
ONGL是ObjectGraphic Navigation Language(对象图导航语言)的缩写,它是一个开源项目。 Struts 2框架使用OGNL作为默认的表达式语言。
OGNL使用方法
1、 在JSP页面中使用
首先要引入strust标签:
<%@taglib prefix="s" uri="/struts-tags"%>
2、再直接使用ONGL代码:
BBB : <s:property value="@java.lang.Runtime@getRuntime().exec('calc')"/>
CCC : <s:property value="@java.lang.Math@random()"/>
3、重启服务,观察出现报错
4、需要配置struts.xml,允许调用静态方法:
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
5、在java代码中使用
在execute()中加入以下代码:
OgnlContext context = new OgnlContext(); Object obj = Ognl.getValue("@java.lang.Runtime@getRuntime().exec('calc')", context);
System.out.println(obj);
并引入相应的包。
6、通过Ognl.getValue执行ONGL表达式