1 導包
2 參照開發包自帶的例子在web.xml文件中配置
3 參照開發包自帶的例子編寫Action類和配置struts.xml文件
<struts>
? ? <package name="demo" namespace="/hello/word">
? ? ? ? <action name="test" class="cn.yue.struts2Demo.web.action.TestAction" method="sayHello">
? ? ? ? </action>
? ? </package>
</struts>
public class TestAction {
public String sayHello()
{
try {
ServletActionContext.getResponse().getWriter().println("hello word!");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
定位包 ?只要一旦追溯到了一個最匹配的上層包名,不管這個包中是否存在要訪問的Action,都不會再追溯更上層的包名了。
定位action 一旦定位到了某個包下,接著就會在這個包中查找action。由于struts會追溯上層包的特點,所以,用某個包的名稱空間的子目錄形式也可以訪問到該包中的Action,前提是該子目錄不存在對應的名稱空間。
? ? ? ? ? ?namespace屬性可以設置為空字符串””,即為默認名稱空間,如果struts2定位到的包名中不存在當前要訪問的Action ,struts2接著還會在默認名稱空間尋找該Action,只有在默認名稱空間的包名中還沒找到該action時,才報錯action找不到的錯誤。
配置結果視圖與視圖工作原理
?1 局部視圖:在<action>元素中配置<result>元素
? ? ? ? <action name="test" class="cn.yue.struts2Demo.web.action.TestAction" method="sayHello">
? ? ? ? ? <result name="success">
? ? ? ? ? <param name="location">/WEB-INF/pages/view.jsp</param>
? ? ? ? ? </result>
? ? ? ? ?</action>
?2 全局視圖:在<global-results>元素中配置<result>元素
<global-results>
? ? <result type="plainText">
? ? ?<param name="location">/WEB-INF/pages/view.jsp</param>
?</result>
? ? </global-results>
?3 自定義一個視圖類型
?
public class WelcomeResult implements Result {
private static final long serialVersionUID = -6454914993165364620L;
private String group="yue";
public void setGroup(String group) {
this.group = group;
}
public void execute(ActionInvocation invocation) throws Exception {
ServletActionContext.getResponse().reset();
ServletActionContext.getResponse().getWriter().println(group+",welcome to you!");
}
}
<action name="test3" class="cn.yue.struts2Demo.web.action.TestAction" method="sayHello">
? ? ? ? <result name="success" type="welcome">
? ? ? ? <param name="group">zhenhua</param>
? ? ? ? </result>
? ? ? ? </action>
? ? ? ??
? ? ? ??
? ? ? ?<!-- ?自定義視圖 -->
? ? <result-types>
? ? <result-type name="welcome" class="cn.yue.struts2Demo.web.result.WelcomeResult"></result-type>
? ? </result-types>
? ?
? ?
?常量配置
?struts-default.xml?
struts-plugin.xml?
struts.xml?
struts.properties?
web.xml?
?<constant name=“struts.action.extension” value=“do,go”/>
?
?重加載xml文件 ?
?tomcat 設置context添加<Context reloadable="true">
?struts.configuration.xml.reload,
? default.properties文件中 struts.devMode 設為true 在struts.xml中配置 <constant name="struts.devMode" value="true"></constant>
Struts.xml中的默認值與更多配置細節
? 1 在根元素<struts>下可以使用include子元素引入其他的配置文件
? 2 <action>元素的method屬性可以不設置,默認為execute;class屬性可以不設置,默認為ActionSupport。?
? 3 ? <result>元素的type屬性和name屬性都可以不設置,默認值分別為dispatcher和success
? 4 ? 在<package>元素下配置<default-action-ref>子元素,用于說明在該包下不存在的action路徑映射,都可以統交給一個默認的<action>元素去處理。
? 5 ? 在<package>元素下的<default-class-ref>子元素,用于配置該包下的<action>元素的class屬性的默認值,前面說的默認值為ActionSupport正是通過這個元素配置的。
? 6 ? 使用Config Browser Plugin瀏覽已經裝載的配置信息和列出各個包名稱空間下的所有Action的訪問鏈接。