0

I need to create an action in my controller to generate excel file. The problem is that if error occurs, the page is changed but I would like to stay on the same page showing that error.

I have this action in my controller:

@RequestMapping(value="/excel", method = RequestMethod.POST)
public String generateExcel(HttpServletResponse response, Model model)

I would like to stay on the same page in case of error:

    if(noError){
      // generate Excel
      response.setHeader("Content-disposition","attachment; filename= "excel.xls");
      response.setContentType("application/vnd.ms-excel");
      //...
      return "";
    } else {
      // stay on the same page and show error
      // TODO
      return ?;
    }

My excel generation is working fine but when error occurs, the new page is shown. I can't make ajax call to generate excel. Can someone help me?

NikNik
  • 2,191
  • 2
  • 15
  • 34

2 Answers2

2

use GetMapping:

@GetMapping(value = "/download")
public void download(
        @RequestParam("fileReference") String fileReference, // sample param
        HttpServletResponse response) throws IOException {
    Assert.hasText(fileReference);
    try {
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=myfilename.pdf");
        response.setContentLength(...);
        response.setBufferSize(...);
        response.getOutputStream().write(...);
    } finally {
        response.getOutputStream().close();
    }
}

then open your link using

target="_blank"
Davide Consonni
  • 2,094
  • 26
  • 27
0

Redirect to the same page can be an option. Keep in mind if you will refresh the page you will loose all the information in the page. I am just saying in case this controller will be in charge of saving.

OEH
  • 665
  • 11
  • 29
  • As you said, if I recall the same page, I will lose all informations in the page but I would like to preserve them. – NikNik Mar 06 '17 at 11:46
  • You can use Ajax to avoid reloading or you can repopulate using model addattribute – OEH Mar 06 '17 at 11:54
  • Yes but with ajax I can't download the file. I'm not using model attribute because I'm populating datatable with some data that returns from web service. So I would like to avoid the "second" call. Thanks anyway – NikNik Mar 06 '17 at 12:14