Struts2零配置

一、简介

Struts2零配置的使用方式体现了“约定优于配置”的开发思想,通过遵循一定的约定规则或使用一些专门的注解,省略XML文档中的配置信息达到简化开发的目的。

二、HelloWorld

我们首先通过一个简单的例子感受一下Struts2零配置的工作方式。

1.要求:不使用struts.xml配置文件访问Action类,并转向到一个结果页面。

2.做法:

①加入JAR包:struts2-convention-plugin-2.3.15.3.jar

②在index.jsp页面中添加超链接

<a href= "${pageContext.request.contextPath }/hello-world">HelloWorld</ a>

③创建/WEB-INF/content/hello-world.jsp

<h1> HelloWorld</h1 >

3.分析

以上操作相当于如下配置

<action name ="hello-world"

        class= "com.opensymphony.xwork2.ActionSupport"

        method= "execute">

     <result name= "success">/WEB-INF/content/hello-world.jsp </result >

</action >

在Struts2零配置工作模式下,结果资源默认保存在/WEB-INF/content目录下,文件名和URL地址一致。

三、创建Action类

①包的要求

Convention插件会在名为struts、struts2、action或actions的包下查找Action类。参照如下配置

<constant name="struts.convention.package.locators" 

value= "action,actions,struts,struts2"/>

说明:以上配置可以在如下文件中找到

struts2-convention-plugin-2.3.15.3.jar/struts-plugin.xml

例如:

com.atguigu.struts

com.atguigu.user.struts2

com.atguigu.book.action.show

com.atguigu.order.actions

②Action类的要求

实现com.opensymphony.xwork2.Action接口或类名以Action结尾。参照如下配置

<constant name= "struts.convention.action.suffix" 

value="Action"/>

例如:

com.atguigu.actions.MainAction

com.atguigu.actions.products.Display (implements com.opensymphony.xwork2.Action)

com.atguigu.struts.company.details.ShowCompanyDetailsAction

 

本教程由尚硅谷教育大数据研究院出品,如需转载请注明来源,欢迎大家关注尚硅谷公众号(atguigu)了解更多。