Wiki源代码使用 XWiki 编写一个 add 接口
由 Qiongpan Ke 于 2023-07-08 最后修改
隐藏最后作者
| author | version | line-number | content |
|---|---|---|---|
![]() |
1.1 | 1 | {{groovy}} |
| 2 | import org.xwiki.velocity.tools.JSONTool; | ||
| 3 | |||
![]() |
2.1 | 4 | // 如果传入 a 和 b 两个参数,则计算两者相加结果,并以 JSON 报文格式返回,否则展示页面内容。 |
![]() |
1.1 | 5 | def a = request.getParameter("a"); |
| 6 | def b = request.getParameter("b"); | ||
| 7 | if (a && b) { | ||
| 8 | def result = Integer.valueOf(a) + Integer.valueOf(b); | ||
| 9 | def json = new JSONTool().serialize(Collections.singletonMap("result", result)); | ||
| 10 | response.setContentType("application/json"); | ||
| 11 | def outputStream = response.getOutputStream(); | ||
| 12 | outputStream.println(json); | ||
| 13 | outputStream.close(); | ||
| 14 | } | ||
| 15 | {{/groovy}} | ||
| 16 | |||
| 17 | 在浏览器中访问本页面时,可以看到此信息。想要完成计算,可以对本页面地址发起 HTTP-POST 请求,例如: | ||
| 18 | |||
| 19 | {{code language="sh"}} | ||
| 20 | curl -fsSL --form 'a=123' --form 'b=456' https://www.keqiongpan.cn/bin/technology/tools/xwiki/add | jq . | ||
| 21 | {{/code}} | ||
| 22 | |||
| 23 | 执行结果如下: | ||
| 24 | |||
| 25 | {{code language="json"}} | ||
| 26 | { | ||
| 27 | "result": 579 | ||
| 28 | } | ||
| 29 | {{/code}} | ||
| 30 | |||
| 31 | 或者可通过如下 HTML 表单,即时发起计算请求: | ||
| 32 | |||
| 33 | {{example}} | ||
| 34 | {{html}} | ||
| 35 | <form action="" method="POST"> | ||
| 36 | <p>a = <input type="text" name="a" value="123" /></p> | ||
| 37 | <p>b = <input type="text" name="b" value="456" /></p> | ||
| 38 | <p><input type="submit" value="计算 a + b 的结果" /></p> | ||
| 39 | </form> | ||
| 40 | {{/html}} | ||
| 41 | {{/example}} |

粤公网安备 44011802000481号 粤ICP备2020117634号