1:導入相應的jar包
2:在web.xml中加上下面的配置
<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>
這樣你的所有請求就會交給struts框架來處理了
3:你的相應action類要繼承ActionSupport
4:在struts.xml配置相應的action
struts.xml中的一些配置
<!-- 開發的時候配置這個有利於調試程序-->
<constant name="struts.devMode" value="true" />
<!-- 瀏覽器是否進行緩存處理,建議開發階段用false -->
<constant name="struts.serve.static.browserCache" value="false"/>
<!-- 修改配置文件是否自動加載無需重啓服務器 建議開發階段用true -->
<constant name="struts.configuration.xml.reload" value="true"/>
<!--請求url後綴默認爲 struts.action.extension=action,,
那麼你地址後面可以加action或者什麼都不加
-->
<!-- 請求url後綴的必須爲action或do -->
<constant name="struts.action.extension" value="action,do"/>
<!-- 有這句namespace和action中的name值之間不允許插入其他值 -->
<constant name="struts.mapper.alwaysSelectFullNamespace" value="true"/>
在struts.xml中可以引入多個配置文件,在開發中比較常用
每個成員寫自己的配置,在struts.xml引入你的配置文件
防止多個人同時操作struts.xml照成不必要的影響
<struts>
<include file="xxx.xml"/>
</struts>
在頁面中使用<s:set name="theme" value="'simple'" scope="page" />
就可以防止struts框架給你添加不必要的主題代碼
也可指定自己指定的樣式<s:set name="theme" value="%{myTheme}" scope="page" />
如果在struts.xml中配置<constant name="struts.ui.theme" value="simple"/>
那麼你的每個頁面都不會添加不必要的主題代碼
請求重定向
<result name="success" type="redirect">
<param name="location">/toredirect.jsp</param>
<param name="username">abc</param>
<param name="password">123</param>
</result>
param中的name屬性的特殊值(能被框架直接識別的如:location)可以在struts核心包中org.apache.struts2.dispatcher.ServletRedirectResult
這個類中可以找到這些值
struts框架會自動將地址拼接成/toredirect.jsp?username=abc&password=123
在jsp頁面直接用${param.username}就可得到參數的值abc
重定向到另一個action
<action name="redirect_action">
<result type="redirectAction">index</result>
</action>
重定向到另外package下的action
<action name="redirect_action2">
<result type="redirectAction">
<param name="actionName">aaa</param>
<param name="namespace">/test</param>
</result>
</action>
將jsp頁面直接顯示在瀏覽器窗口,不解析頁面中的標籤
<action name="plain_text">
<result type="plainText">
<!-- name="actionName"值在 org.apache.struts2.dispatcher包下面的PlainTextResult文件中 -->
<param name="location">/index.jsp</param>
<!-- 指定文件的讀取的編碼 name="charSet"的值可在覈心包org.apache.struts2.dispatcher下面的PlainTextResult文件中-->
<param name="charSet">UTF-8</param>
</result>
</action>
配置全局的result,那麼在該package下的action中沒有找到相應的result時會用這個全局的result
<package >
<global-results>
<result name="miss">/WEB-INF/hello.jsp</result>
</global-results>
</package>
爲action中的屬性注入值(當然你可以在某個方法中直接對屬性賦予相應的值)
<action name="demo1" class="cn.axin.Demo1Action">
<!-- 爲Demo1Action中的username屬性(名字可以不是username)注入值(但是注意Demo1Action中一定要有setUsername方法) -->
<param name="username">zhangsan</param>
<result>/hello.jsp</result>
</action>
在jsp頁面取出Demo1Action中username屬性的值
${username}
這裏username是和Demo1Action中的getUsername方法對應的,否則取不到數據
<!-- 通配符的使用 -->
<action name="good_*" class="cn.axin.ThirdAction" method="{1}">
<result>/third.jsp</result>
</action>