如何在spring mvc中的动作之前发送响应 [英] How to send response before actions in spring mvc

查看:170
本文介绍了如何在spring mvc中的动作之前发送响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的弹簧控制器功能接收到大量数据。
我想返回200 OK,假设数据结构正确,之后我想执行处理,这可能需要一段时间。

Say that my spring controller function receives a large amount of data. I want to return 200 OK, given that the data is structured right, and after that I want to perform the processing, which might take a while.

根据我的理解,发送响应的唯一方法是通过 return 命令。但我不想结束响应发送功能。

To my understanding the only way to send response is by return command. But I don't want to end the function on response send.

还有其他方法可以在函数中间向客户端发送响应吗?

Are there other ways to send response to client at the middle of the function?

创建新线程运行是显而易见的,但其他语言(JS)让你更优雅地处理它。

Creating a new thread run is obvious but other languages (JS) let you handle it more elegantly.

@RequestMapping(value = Connectors.CONNECTOR_HEARTBEAT, method = RequestMethod.POST)
public ResponseEntity<String> doSomething(@RequestBody List<Message> messages) {
    HttpStatus code = (messages!=null && !messages.isEmpty()) ? HttpStatus.OK
            : HttpStatus.NOT_FOUND;
    return new ResponseEntity<String>(res, code);
   // how do I add code here??
}


推荐答案

您当然可以进行处理发送回复后。更通用的方法是使用 HandlerInterceptor afterCompletion 方法。通过构造,它将在响应发送到客户端后执行,但它会强制您将控制器中之前部分中的逻辑拆分为 之后的拦截器中的一部分。

You can of course do processing after sending the response. The more general way would be to use the afterCompletion method of a HandlerInterceptor. By construction, it will be executed after the response have been sent to client, but it forces you to split you logic in 2 components the before part in controller, and the after part in the interceptor.

另一种方法是忘记Spring MVC机器并在控制器中手动提交响应:

The alternative way is to forget Spring MVC machinery and manually commit the response in the controller:

@RequestMapping(value = Connectors.CONNECTOR_HEARTBEAT, method = RequestMethod.POST)
public void doSomething(@RequestBody List<Message> messages, HttpServletResponse response) {
    int code = (messages!=null && !messages.isEmpty()) ? HttpServletResponse.SC_OK
            : HttpServletResponse.SC_NOT_FOUND;
    if (code != HttpServletResponse.SC_OK) {
        response.sendError(code, res);
        return;
    }
    java.io.PrintWriter wr = response.getWriter();
    response.setStatus(code);
    wr.print(res);
    wr.flush();
    wr.close();

    // Now it it time to do the long processing
    ...
}

注意void返回代码,通知Spring响应已在控制器中提交。

Note the void return code to notify Spring that the response have been committed in the controller.

作为一个优势,处理仍然出现在同一个线程中,因此您可以完全访问会话作用域属性或Spring MVC或Spring Security使用的任何其他线程局部变量...

As a side advantage, the processing still occurs in the same thread, so you have full access to session scoped attributes or any other thread local variables used by Spring MVC or Spring Security...

这篇关于如何在spring mvc中的动作之前发送响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆