一、开发插件类
接口
package com.neuqsoft.symphony.plugin; public interface HelloWorld{ String hello(); }
实现类
package com.neuqsoft.symphony.plugin.impl; public class HelloWorldImpl implements HelloWorld{ public String hello(){ return "HelloWorld"; } }
二、将插件打包,在将插件打包的时候,除了要将与插件相关的类文件打包,还要将文件名为struts-plugin.xml的xml文件放在Jar文件的根目录中,在加载时struts2框架会搜寻根目录中存在struts-plugin.xml文件的Jar文件。我们刚才开发的插件的struts-plugin.xml文件的内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <bean type="com.neuqsoft.symphony.plugin.HelloWorld" class="com.neuqsoft.symphony. plugin.impl.HelloWorldImpl" name="HelloWorld"/> </struts>
说明:其中bean的type属性指明了插件的接口,class属性指明了实现类,name属性指明了bean的名字。
编辑好xml文件后将它和类文件一起打包就可以了(注意将它放在和顶层包同一层次的目录中,在这里是com)jar -cvf MyPlugin.jar com,struts-plugin.xml,这条命令会生成一个名为MyPlugin.jar的归档文件。
三、测试我们的插件,为了验证我们刚才开发的插件可以正常工作,现在新建一个名为pluginTest的web工程,在WEB-INF/lib中除了放置构建struts2必须的Jar包以外将我们自己开发的Jar也放在这个目录下面。
3.1、开发一个Action
package com.neuqsoft.symphony.action; //import import java.util.*; import com.neuqsoft.symphony.plugin.HelloWorld;//我们的插件的对外接口 import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.inject.Inject; public class MyAction extends ActionSupport { private static final long serialVersionUID = 1L; private HelloWorld plugin; private String message; @Inject //插件资源依赖容器注入,"HelloWorld"是在struts-plugin.xml中指定的bean名称 public void setContainer(Container container) { plugin=container.getInstance(HelloWorld.class,"HelloWorld"); } @Override public String execute(){ message=plugin.hello(); return SUCCESS; } public String getMessage() { return this.message; } }
3.2、编辑struts.xml文件(放在WEB-INF/classes目录下)
<!DOCTYPE struts PUBLIC "- //Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http: //struts.apache.org/dtds/struts-2.0.dtd" > <struts> <package name= "default" extends="struts- default"> <action name="MyAction" class="com.neuqsoft.symphony.action.MyAction"> <result>/show.jsp</result> </action> </package> </struts>
3.3、定义JSP页面show.jsp
<%@ taglib prefix= "s" uri= "/struts-tags" %> <html> <head><title>Hello World!</title></head> <body><h2><s:property value= "message"/></h2> </body> </html>
3.4、接下来就可以将我们的web工程部署在Tomcat里面了,然后在浏览器中输入 http://localhost:8080/pluginTest/MyAction.action 查看结果吧。