1.環境搭建
1.建立web項目
2.建立Struts2的配置文件(struts.xml)
將Struts2 的空項目 中的配置文件 (struts.xml)復制到項目的 src目錄下
struts2.x配置文件的默認存放路徑是在/WEB-INF/classes目錄下,也就是說,把struts.xml放在src的目錄下
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4"http://struts.apache.org/dtds/struts-2.0.dtd"> 5 6 <struts> 7 8 <!-- <constant name="struts.enable.DynamicMethodInvocation" value="false" /> 9 <constant name="struts.devMode" value="false" /> 10 11 <include file="example.xml"/> 12 13 14 15 <packagename="default" namespace="/" extends="struts-default"> 16 <default-action-ref name="index" /> 17 <action name="index"> 18 <result type="redirectAction"> 19 <param name="actionName">HelloWorld</param> 20 <param name="namespace">/example</param> 21</result> 22 </action> 23 </package> 24 --> 25 <!-- Add packages here --> 26 <constant name="struts.devMode" value="true" /> 27 <package name="default" namespace="/" extends="struts-default"> 28 <action name="helloy"> 29 <result> 30 hello.jsp 31 </result> 32 </action> 33 </package> 34 35 </struts>
3.復制Struts2相應的jar包及第三方包
4.修改對應的web.xml,建立struts2的filter(參考struts自帶的項目)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <filter> 12 <filter-name>struts2</filter-name> 13 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 14 </filter> 15 16 <filter-mapping> 17 <filter-name>struts2</filter-name> 18 <url-pattern>/*</url-pattern> 19 </filter-mapping> 20 </web-app>
Struts2的訪問過程
Struts2的訪問過程:
1.客戶機發送請求 (http://localhost:8080/struts2/hello.action)
2.請求發送到tomcat,tomcat查看web.xml文件,web.xml裏面配置了使用哪個過濾器進行過濾,要過濾哪些請求
3.通過web.xml指導 要使用struts2Filter 這個過濾器,調用這個過濾器,這個過濾器會去參考stuts.xml這個文件
4.struts.xml裏面配置了,namespace("/") action("helloy")訪問哪個action result("hello.jsp")返回哪個結果 http://localhost:8080/Struts_01/helloy.action
5.filter參考了struts.xml之後,將請求轉發到 hello.jsp
6.hello.jsp 返回顯示
註:
如果沒有編寫對應的Action類,不會報錯,只要在struts.xml文件中,使用action標簽對某個Action進行了註冊,
那麽會自動執行result為 success 的結果
struts2 為什麽要這樣做,為什麽不直接訪問 hello.jsp?
作用: /*將你的請求和展現(視圖)分開*/,
每個請求都要經過struts的中轉,如果直接訪問hello.jsp,那麽請求裏面就帶有了你所需要的展現,如果需要其他的展現,則需要對請求進行修改
而使用struts之後,只需要修改struts.xml這個配置文件就可以了
/*之所以復雜化,是為了可擴展性*/
namespace 決定了action的訪問路徑,默認為 "" 即 不指定即為 namespace=""
namespace 可以寫為/,或者/xxx,或者/xxx/yyy,對應的action訪問路徑為 /index.action /xxx.index.action /xxx/yyy/index.action
namespace 最好也用模塊來進行命令
1.環境搭建