Java中的SSH框架之struts2
阿新 • • 發佈:2019-01-24
SSH:struts2+spring+hibernate,三個框架整合在一起。
首先,為專案增加struts2框架:
1、首先需要使用IDE建立一個web project,我使用的是myeclipse6.5
2、引入struts2的jar包。
在網上查到的大多數都是引入5個核心jar包:commons-logging-1.0.4.jar、freemarker-2.3.13.jar、ognl-2.6.11.jar、struts2-core-2.1.6.jar、xwork-2.1.2.jar
但是當struts2框架搭建好後,啟動服務系統會丟擲異常:
Unable to load configuration. - bean - jar:file :/D:/Program%20Files/Apache%20Software%20Foundation/Tomcat%206.0/webapps/s2shFrame/WEB-INF/lib/struts2-core-2.1.6.jar!/struts-default.xml:46:178
如果丟擲這個異常,則需要在額外引入:commons-fileupload-1.2.1.jar 、commons-io-1.3.2.jar 兩個JAR包:
3、JAR包匯入後,需要在web.xml需要配置struts資訊。
<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>
4、在專案src目錄下增加struts.xml,在xml檔案寫入
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
</struts>
5、到此為止,一個struts2框架的搭建算是完成了。
現在使用struts2框架簡單測試下
首先修改index.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<form name="fm" action="struts2Test" method="test">
</form>
<input type="submit" name="button" onclick="fm.submit()">
</body>
</html>
注意form標籤中的一些用法。
配置sturts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<action name="struts2Test" class="sturts2.test.testAction" method="test">
<result name="success" type="redirect">index1.jsp</result>
</action>
</package>
</struts>
建立testAction類並增加test方法:
package sturts2.test;
import com.opensymphony.xwork2.ActionSupport;
public class testAction extends ActionSupport{
public String test(){
return SUCCESS;
}
}
增加返回結果的JSP頁面index1.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
hello World!
</body>
</html>