Jenkins - 如何将 url 绑定到 returns json 字符串的 java 方法?

Jenkins - How to bind a url to a java method which returns json string?

我正在练习开发一个 jenkins 插件。我想在前端发送一个带有一些 cookie 的 ajax 请求以进行后端处理,然后接收一些 json 响应以继续处理我的前端逻辑。我是否可以使用 StaplerRequestStaplerResponse 等参数将 url 绑定到后端 java 方法,并从方法中简单地获取返回的 json作为我的回应?

是的,您可以创建简单的 Rest 方法,它只消耗 JSON 中的响应,就像这样

@POST
@Path("/somemethod")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CommonResponseBean somemethod() {
    return response(); // return CommonResponseBean, this will automatically converted into json using jackson
}

四处搜索后,我找到了一个网站introducing how Jenkins stapler works.特别是操作方法可能对我有帮助

根据我查到的文档:

Action Method

If url is of the form "/fooBar/...." and node has a public "action" method named doFooBar(...), then this method is invoked.

检索 json 响应, 在前端,

$.ajax({
    url: "./someUrl/",
}).done(doSomethingOnData(data));

在后台定义对应的action方法:

public void doSomeUrl(StaplerRequest request, StaplerResponse response) {
    Cookie[] myCookies = request.getCookie();
    doSometingBasedOnCookies(myCookies);
    response.setStatus(200);
    response.setContentType("application/json;charset=UTF-8");
    String myJson = getJson();
    response.getWriter().print(myJson);
}