Struts2约定(了解)
1 什么是约定
使用约定可以连注解都不写,是真正的零配置,但是它的能力有限,所以这种方式不可取的。
l Struts2会对Action的命名,以及Action的包名都有限制;
l Struts2会对结果页面的存放路径,以及结果页面的名称也都有限制。
使用约定与使用注解一样,也要导包:struts2-convention-plugin-2.3.15.jar
1 约定对Action的限制
约定Action类名:
要求Action的命名必须以“Action”为后缀,例如:UserAction、BookAction等等。可以使用下面常量来修改后缀限制:
<constant name="struts.convention.action.suffix" value="Action"/>
约定Action包名:
要求Action必须放到action、actions、struts、struts2包中。例如:cn.itcast.action、cn.itcast.sturts、cn.itcast.action.user等等。可以使用下面常量来修改Actoin的包
<constant name="struts.convention.package.locators" value="action,actions,struts,struts2"/>
2 通过Action的限制得到访问路径
上面已经知道约定对Action的限制,现在通过Action的包名和类名得到它的访问路径
例如:cn.itcast.action.UserAction,它的访问路径为/user.action
例如:cn.itcast.action.user.UserAction,它的访问路径为/user/user.action。因为在约定包action后面还有一层包user,那么这一层就是名称空间了。
例如:com.action.cn.itcast.user.UserAction,它的访问路径为/cn/itcast/user/user.action。
例如:cn.itcast.action.user.UserListAction, 它的访问路径为/user/user-list.action。当Action名称由多个单词构成,那么在访问路径中使用“-”来连接多个单词。3
3 通过Action的限制得到结果页面路径
Struts2约定限制结果页面必须放到/WEB-INF/content/目录中,可以通过下面常量来修改这个限制。
<constant name="struts.convention.result.path" value="/WEB-INF/content/"/>
当cn.itcast.action.UserAction返回结果为success时,Struts会依次查找如下结果页面:
l /WEB-INF/content/user-success.jsp;
l /WEB-INF/content/user-success.html;
l /WEB-INF/content/user.jsp
当cn.itcast.action.user.UserListAction返回的结果为error时,Struts会依次查找如下结果页面:
l /WEB-INF/content/user/user-list-error.jsp;
l /WEB-INF/content/user/user-list-error.html;
l /WEB-INF/content/user/user-list.jsp