先貼了本帖地址,以免被爬 http://www.cnblogs.com/linghaoxinpian/p/6898779.html
本教程將會通過安裝struts2框架來創建一個簡單的應用程序。
雖然Struts 2框架簡單易用,但在開始之前,必須有一定的J2EE技術的儲備,包括:
- Java
- Filters, JSP, and Tag Libraries
- JavaBeans
- HTML and HTTP
- Web Containers (such as Tomcat)
- XML
Java Requirements
Struts 2 需要Servlet API 2.4 或是更高的版本, JSP 2.0 或是更高的版本, Java 7 或是更高的版本。
我們的第一個struts2項目
你可以在我的百度網盤上下載樣例項目 https://pan.baidu.com/s/1pL7DgwF
Step 1 - 創建一個Java Web Application
這里我用的是Myeclipse,而不是Maven。取名為struts-basic
Step 2 -添加 index.jsp
在WebRoot/index.jsp下
1 <!DOCTYPE html> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> 3 <html> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Basic Struts 2 Application - Welcome</title> 7 </head> 8 <body> 9 <h1>Welcome To Struts 2!</h1> 10 </body> 11 </html>
接着運行,應該是這個樣子:
到這了應該沒什么難度吧
Step 3 -添加 Struts 2 的jar文件到項目中
在struts2的官網里下載jar包,
Step 5 - 添加 struts2 的過濾器
為了確保struts2能在你的web應用中運行,需要在web.xml中添加過濾器設置來啟用struts2,如下:
web.xml Servlet Filter
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
注意上面的 <url-pattern>/*</url-pattern> 意味着struts2的過濾器將會被應用到這個web 應用的所有URL上。
新版的myeclipse默認是沒有web.xml的,自己手動新建一個就行了,修改后的web.xml應該是這個樣子:
Step 6 - 創建 struts.xml
struts2 可以使用其它的XML配置文件或者是annotation(注解)來指定URL(/index.action)與處理類(Index類)、視圖文件(index.jsp)之間 關聯,對於我們這個基礎項目,我將只使用最簡單的配置方法,注意struts.xml文件必須放在src的根目錄下(struts_basic/src/struts.xml),因為發布后src下的文件會被IDE轉移到項目的class path的根目錄下,這是struts2的規范。
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> <constant name="struts.devMode" value="true" /> <package name="struts_basic" extends="struts-default"> <action name="index"> <result>/index.jsp</result> </action> </package> </struts>
這個最簡便的配置文件告訴struts2框架,如果訪問的URL是http://localhost:8081/struts_basic/index.action 或是http://localhost:8081/struts_basic/index 則轉發到index.jsp視圖
Step 7 - 運行程序