(搜藏)更改struts2的訪問后綴名.action為.do或者其他的
<DIV id=articleBody class=articleContent>設置Struts 2處理的請求后綴及<SPAN class=hilite2>Action</SPAN>調用</DIV>
<DIV class=articleContent>1、在struts2中默認處理的請求后綴為<SPAN class=hilite2>action</SPAN>,我們可以修改struts.xml 和struts.properties來修改默認的配置,在struts.xml中<struts>添加子接點<constant name=”struts.action.<SPAN class=hilite3>extension</SPAN>” value=”do” /></SPAN> 或者是修改struts.properties文件 添加struts.action.<SPAN class=hilite3>extension</SPAN> = do</SPAN>這都是一樣的效果
注意:struts.xml 和struts.properties的都放在src下發布的時候會自動拷貝到WEB-INF/classes下
2、如何調用Action的方法 這是本章的重點
1) 如果在Action中只有一個 execute方法那么配置好后就會自動訪問這個方法。如果方法名字不是execute 那么我們需要在struts.xml中的Action接點添加一個method屬性為該方法簽名,如下:
<action method=”hello” name=”helloAction” class=”com.struts2.chapter5.HelloAction”></action>
這樣就會調用hello的方法!
2)這是一個控制器負責處理一個請求的方式,但這樣就會造成很多的Action類,給維護帶來困難。所以可以讓一個 Action可以處理多個不同的請求。對于一個學生信息管理模塊來說,通過一個Action處理學生信息的添、查、改、刪(CRUD)請求,可以大大減少 Action的數量,有效降低維護成本。下面代碼讓我們可以使用通配符來操作
public class StudentAction{
public String insertStudent(){…}
public String updateStudent(){…}
}
<action name=”*Student” class=”com.struts2.chapter5.StudentAction” method=”{1}”>
<result name=”success”>/result.jsp</result>
</action>
仔細觀察一下,發現name屬性中有一個”*”號,這是一個通配符,說白了就是方法名稱,此時method必須配置成method={1},才能找到對應的方法。現在,如果想調用insertStudent方法,則可以輸入下面的URL進行訪問:http://localhost:8081 /Struts2Demo/ insertStudent.do,如果想調用updateStudent方法,則輸入http://localhost:8081/Struts2Demo/updateStudent.do即可。格式如何定義,完全由程序員決定,”*”放在什么地方,也是可以自定義的。
3)對于上面的StudentAction我們還可以這樣配置
<action name=”studentAction” class=”com.struts2.demo.StudentAction”>
<result name=”success”>/result.jsp</result>
</action>
調用Action的方法還可以通過”Action配置名!方法名.擴展名”
http://localhost:8081/Struts2Demo/studentAction!insertStudent.do
http://localhost:8081/Struts2Demo/studentAction!updateStudent.do
</DIV>