簡介
本文將介紹如何編寫一個提供給後臺接口並使用腳本在前端頁面調用。
使用maven下載XWiki提供的模板項目
保證你的maven已經安裝,然後執行命令
mvn archetype:generate \
-DarchetypeArtifactId=xwiki-commons-component-archetype \
-DarchetypeGroupId=org.xwiki.commons \
-DarchetypeVersion=10.11.3
下載成功之後會詢問項目的自定義預設信息
當你輸入’Y’確認了以後就會在本地生成項目了
模板項目裏邊的文件列表如下
pom.xml
src/main/java/com/fxp/HelloWorld.java
src/main/java/com/fxp/internal/DefaultHelloWorld.java
src/main/java/com/fxp/internal/HelloWorldScriptService.java
src/main/resources/META-INF/components.txt
src/test/java/com/fxp/HelloWorldTest.java
介紹幾個比較重要的文件
- components.txt:用於實例的注入,你編寫的bean都要在此文件中聲明才能注入到應用上下文中。
- HelloWorldScriptService.java:用於把你的bean暴露給前端頁面的腳本,腳本可以通過services對象找到你的bean。
如何寫一個bean並且暴露給前端頁面
第一步:編寫你的bean
package com.fxp.internal;
import com.fxp.HelloWorld;
import org.xwiki.component.annotation.Component;
import javax.inject.Singleton;
/**
* Implementation of a <tt>HelloWorld</tt> component.
*/
@Component
@Singleton
public class DefaultHelloWorld implements HelloWorld
{
@Override
public String sayHello()
{
return "hello I come from custom jar!!";
}
}
第二步:在components.txt中聲明你的bean
com.fxp.internal.DefaultHelloWorld
com.fxp.script.HelloWorldScriptService
第三步:注入到ScriptService的bean中,通過該bean的方法暴露出去。
package com.fxp.script;
import org.xwiki.component.annotation.Component;
import org.xwiki.script.service.ScriptService;
import com.fxp.HelloWorld;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
/**
* Make the HelloWorld API available to scripting.
*/
@Component
@Named("hello")
@Singleton
public class HelloWorldScriptService implements ScriptService
{
@Inject
private HelloWorld helloWorld;
public String greet()
{
return this.helloWorld.sayHello();
}
}
把項目打成jar包並且導入到XWiki中
在項目目錄下使用mvn install
命令生成jar包,如果成功可以在打印信息的最後看到生成的jar包目錄,如下
再把jar包複製到XWiki應用的lib目錄下
#我是用docker部署的,所以要用docker cp命令
docker cp C:\Users\Administrator\.m2\repository\com\fxp\test-component\1.0-SNAPSHOT\test-component-1.0-SNAPSHOT.jar 747f836b8a05:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib
重啓XWiki項目
到此,jar包部署完成,下一步測試一下我們的jar包。
在前端使用腳本訪問你的接口
我們編寫的ScriptService的bean方法可以在前端腳本中使用services對象引用到,在XWiki編輯框中輸入如下腳本(hello就是我們使用@Named(“hello”)聲明的對bean名稱)
點擊保存並查看,效果如下
總結
到此,從後端API到前端腳本的流程都打通了。