从控制器(spring mvc)异步获取响应

时间:2017-09-07 02:06:39

标签: java spring spring-mvc asynchronous

我有控制器方法处理“下载”按钮点击我的页面。此方法调用我们的服务,在那里进行查询。 我的问题是Service需要大约20-30秒才能执行查询,然后将它返回到控制器并放到outputStream返回给用户。因此,在实际下载开始之前,用户被阻止并且在30秒内无法执行任何操作。

如何解决此问题?我不希望我的用户等待。我是初学mvc和异步编程的新手。那么,请解释一下,我怎么能异步地做到这一点?

@RequestMapping(value = "/download")
	public void downloadCSV(@RequestParam(“vendorId”), @RequestParam(“startDateString”),@RequestParam(“startDateString”),
			HttpServletResponse response) throws IOException 
	{

List<Objects> listFromService = getListFromService();
	
		String fileName = vendorId + "_metrics.csv";
		response.setHeader("Content-disposition", "attachment;filename="+fileName);
		ServletOutputStream outputStream = response.getOutputStream();
	

		
		listFromService.stream().forEach(item -> {
			try {
				processListItem(item, outputStream);
			} catch (IOException e) {
			
				e.printStackTrace();
			}
		});
		outputStream.flush();
	}

1 个答案:

答案 0 :(得分:1)

您可以使用从视图(JSP)到控制器的AJAX调用,如下所示。

JSP表单:

<FORM NAME="form1" METHOD="POST">
    <INPUT TYPE="BUTTON" VALUE="Download" ONCLICK="downloadCSV()">
</FORM>

Ajax函数:

<script type="text/javascript">
    function downloadCSV() {
        console.log("Download called..");

        $.ajax({
            type : "GET",
            url : '${home}/download',
            dataType : "json",
            crossDomain : true,
            success : function(data) {
                processResponse(data);
            },
            error : function(data) {

            }
        });
    }

    function processResponse() {
        console.log("Your response processing goes here..");
    }
</script>
相关问题