簡介
struts2 下載
官網下載地址
最新版是2.5.2,這個版本的一些jar包與舊版本不太一樣,不過變化不大。
這里選擇完整的包(Full Distribution)下載。
下載解壓后的文件結構如下圖:
一個簡單的例子
- tomcat,我使用的tomcat-8.0.37
- jdk,我使用的是jdk-1.8.101
-
eclipse,我使用的是eclipse neon(4.6.0)保證tomcat能夠正常運行。
具體步驟
新建一個Web項目,名稱為HelloWorld
把struts2中相關的jar包復制到WEB-INF/lib文件夾下,最基礎的需要8個jar包:commons-fileupload-1.3.2.jar、commons-io-2.4.jar、commons-lang3-3.4.jar、freemarker-2.3.23.jar、log4j-api-2.5.jar、ognl-3.1.10.jar、struts2-core-2.5.2.jar、javassist-3.20.0-GA.jar
注意:struts2.5之前的版本有點不同,還需要xwork-core.jar,不需要log4j-api.jar。struts2.5把xwork-core.jar合並到了struts2-core.jar中,但是struts2.5如果沒有加入log4j-api.jar,tomcat會啟動失敗,我也不知道為什么。
在web.xml中配置struts2框架的核心控制器StrutsPrepareAndExexuteFilter 。
在src目錄下新建一個業務控制Action類,繼承自com.opensymphony.xwork2.ActionSupport,內容如下:
Action需要在Struts2的核心配置文件struts.xml中進行配置。因此需要創建struts.xml文件,該文件位於src目錄下:
新建一個result.jsp文件,用來action顯示返回的視圖
啟動tomcat,訪問http://localhost:8080/HelloWorld/helloworld.action。如果一切Ok,會出現下面的頁面。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>HelloWorld</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置核心攔截器 --> <filter> <!-- Filter的名字 --> <filter-name>struts2</filter-name> <!-- Filter的實現類 struts2.5以前可能有所不同 --> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <!-- 攔截所有的url --> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="default" namespace="/" extends="struts-default"> <!-- name action的名字,訪問時使用helloworld.action訪問,class:實現類 --> <action name="helloworld" class="com.xiaohuan.action.HelloWorldAction"> <!-- 結果集,即action中SUCCESS返回的視圖 --> <result> /result.jsp </result> </action> </package> </struts>
HelloWorldAction.java
package com.xiaohuan.action; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport{ @Override public String execute() throws Exception { System.out.println("正在執行的Action"); //返回邏輯視圖SUCCESS return SUCCESS; } }
result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>success</title> </head> <body> <h1>恭喜成功配置好基本的struts2環境</h1> <h2>Hello World ,This is result.jsp.</h2> </body> </html>
http://www.vztribe.com/forum.php?mod=viewthread&tid=48&fromuid=1
(出處: VZ部落—化一切為可能)