不,您不能返回两个响应。但是,一种方法是从客户端以异步GET
方式发出相应的请求,当响应可用时,它可以进一步处理响应(可以是成功或失败)。同时客户端(浏览器)可以正常继续。
使用 apache wink 提供的 RESTful 服务非常简单,您只需设置必要的 wink 库,然后通过@Path
注释将服务器端 Java 方法连接到客户端(假设是 Javascript)。
例如,您想在路径your_web_application_context/configuration/check发出这样的请求
然后您的 Java(服务器端)REST 类将如下所示
@Path("/configuration")
public class Configuration { // Some class name
@GET
@Path("/check") // configuration/check comes from your request url
public Response analysis(@Context HttpServletRequest req) {
JSONObject conf = new JSONObject();
try{
myProcess();
return Response.ok().build();
} catch(Exception e) {
e.printStackTrace();
JSONObject response = new JSONObject();
response.put(RESTApplication.ERRORCODE, "S001");
response.put(RESTApplication.MESSAGE, "Error occurs");
return Response.serverError().entity(response).type(MediaType.APPLICATION_JSON).build();
}
}
注意:注解由 wink 库提供@GET
。@Path
现在准备好服务器端,您可以通过客户端的异步调用向服务器端方法发出请求,然后客户端将处理您的请求并返回响应。出于演示目的,我将在客户端使用jQuery 的 get方法。
$.get("<your application context url>/configuration/check",
function(data, status){
// This function is called when the response is available.
// Response data is available in data field.
// Status field tells if the request was success or error occurred.
alert("Data: " + data + "\nStatus: " + status);
}).done(function() {
// This function is called when the response is successfully processed.
// Here you can chain further requests which should only be dispatched
// once the current request is successfully finished
}).fail(function() {
// This function is called when the response is an error.
// Here you can chain further requests which should only be dispatched
// if the current request encounters an error
});
// Statements after $.get function, will continue executing immediately
// after issuing the request. They won't wait for response
// unlike the above "done" and "fail" functions