Search code examples
springjspliferay

Displaying the last page with an error message when using @ResourceMapping


I have a page with a single button (for simplicity). The button asks the server to generate a file and return it. This works without a hitch. When the server has an issue generating the file (for whatever reason), then rather than give back an empty file, nothing happens. This causes the page to be blank (where-as before it would be the last page I was on with a file getting downloaded).

How can I send an error message back to the previous page (without using AJAX for now) from that function? A blank page with the error message is not what I'm looking for.

controller.java

@ResourceMapping
public void getFile(ResourceRequest request, ResourceResponse response) {
    String zipName = "myfile.zip";

    try {
        //Do something that might throw an error

        response.setProperty("Content-Disposition", "attachment; filename=" + zipName);
        response.setContentType("application/zip");
        //Write to output stream here
    } catch(Exception e) {
        myLogger.error("Error from throwable: " + e.getMessage());

        //Send error message to user on the last page without getting a blank screen
    }

view.jsp

${lastError}
<form method="post" action="<portlet:resourceURL/>">
  <input type="checkbox" name="Modify File" value="true" />
  <input type="submit" value="Get File" />
</form>

Solution

  • You get blank page because you did not putting anything to response.

    When making ResourceRequest your response is always ONLY what you put in ResorceResponse, You never get portal's page as a response (not even part of it).

    So what you want to do, as you are trying now, is not possible. You have to change your approach.

    Simplest (not best) workaround would be

    <form method="post" action="<portlet:resourceURL/>" target="_blank">
       <input type="checkbox" name="Modify File" value="true" />
       <input type="submit" value="Get File" />
    </form>
    

    note target="_blank".

    Your controller ...

    @ResourceMapping
    public void getFile(ResourceRequest request, ResourceResponse response) {
      String zipName = "myfile.zip";
    
      try {   
    
        response.setProperty("Content-Disposition", "attachment; filename=" + zipName);
        response.setContentType("application/zip");
    
        //Write to output stream here
    
      } catch(Exception e) {
        myLogger.error("Error from throwable: " + e.getMessage());
        // write the error message to the response stream here.
        response.setContentType("text/plain");
        response.getWriter().print("last error");
      }
    }
    

    This way you get file or error in new window leaving your portal page as is.

    Other options: AJAX or your response could be html with javascript that makes request to your portal page with additional parameter for error, ...