配置Action(二)
Action元素的完整属性
属性 |
是否必需 |
说明 |
name |
是 |
Action的名字,用于匹配请求的URL |
class |
否 |
Action实现类的完整类名 |
method |
否 |
执行action时调用的方法 |
converter |
否 |
应用于action的类型转换器的完整类名 |
Eg:
<action name=”login” class=”org.sunxin.struts2.ch03.action.LoginAction”> <result>/success.jsp</result> <result name=”error”>/error.jsp</result> </action> |
Action的name属性是必须的,其他的属性是可选的。
在为action取名时,默认情况下在名字中是不允许出现斜杠(/)的。
如果想要在名字中出现斜杠,例如<action name=”book/manager” class=”org.sunxin.bookstore.BookManager” />,就需要在struts.xml文件中通过指定
<constant name=”struts.enable.SlashesInActionNames” value=”true” />来打开这个共能。
此外,在为action取名时,尽量不要用. - 否则会出现一些莫名的问题。(create.user) (my-action)。
使用method属性
在软件开发中,经常会用到CRUD操作,CRUD即Create、Read/Retrieve、Update、Delete的首字母缩写。
为了节省action类的数量,通常是在一个action类中编写4个操作。
在NewsAction类中实现CRUD操作:
Package org.sunxin.struts2.ch05.action; Import com.opensymphony.xwork2.ActionSupport; Public class NewsAction extends ActionSupport{ Public String create() throws Exception{ … Return SUCCESS; } Public String execute() throws Exception{ … Return SUCCESS; } Public String delete() throws Exception{ … Return SUCCESS; } Public String edit() throws Exception{ .. Return SUCCESS; } } |
现在的问题是,我们如何才能让框架知道在不同请求到来时,去调用NewsAction中的相应方法呢?要知道,在执行action时,默认调用的方法是execute()
在配置action时,我们可以通过action元素的method属性来指定action调用时的方法。所指定的方法必须遵循与execute()方法相同的格式。
在struts.xml文件中,我们可以为同一个action类配置不同的别名,并使用method属性,
<package name=”default” extends=”struts-default”> 请求/list时,调用NewsAction的execute()方法 <action name=”list” class=”org.sunxin.struts2.ch05.action.newsAction”> <result>/listNews.jsp</result> </action>
请求/create,调用NewsAction的create方法 <action name=”create” class=”org.sunxin.struts2.ch05.action.newsAction”> <result>/create.jsp</result> </action>
请求/edit,调用NewsAction的edit方法 <action name=”edit” class=”org.sunxin.struts2.ch05.action.newsAction”> <result>/editNews.jsp</result> </action>
请求/delete,调用NewsAction的delete方法 <action name=”delete” class=”org.sunxin.struts2.ch05.action.newsAction”> <result>/deleteNews.jsp</result> </action>
</package> |
使用action的method属性可以任意指定处理请求的方法(只要该方法和execute()方法具有相同的格式),这样就可以在同一个类中完成相关的任务,而不需要去编写不同的Action类。