Search code examples
javaportletliferay-7

Java portlet: how to redirect (server side) to serveResource?


(disclaimer: I'm new to portlet development)

I created portlet (in liferay) to serve files. But user first need to fill small form (name, etc.) and then after clicking "save" I put data do database and should serve the file for download.

I do know how to serve file with:

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) 

and save data with action:

@ProcessAction(name = "save")
public void save(ActionRequest actionRequest, ActionResponse actionResponse)

But don't know how to server.transfer from one to another. I can't just call:

serveResource(actionRequest, actionResponse);

because parameters are not compatible.

Also on error I should do:

PortalUtil.copyRequestParameters(actionRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/myForm.jsp");

which is not available for resourceRequest/resourceResponse...

What is proper/elegant way for this kind of redirections in portlets?


Solution

  • For saving forms instead of using processAction, you can directly call the serveResource and save form and serve file from serve method itself.

    You can also take help of Ajax request to submit form.

    <form action="<portlet:resourceURL/>" method="POST">
    ...
    </form>
    
    @Override
    public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse){
    
    //Save_form
    
      if(success){
          //serveFile
          String documentPath = document.getDocumentPath();
    
          File file = getFile(documentPath);
    
          String contentType = MimeTypesUtil.getContentType(file);
    
          long contentLength = file.length();
    
          is = new FileInputStream(file);
    
          ServletResponseUtil.sendFile(
              request, response, document.getDocumentName(), is, contentLength, contentType,
              HttpHeaders.CONTENT_DISPOSITION_INLINE);
    
      }else{
    
          response.getOutputStream("Error submitting form");
          response.getOutputStream().flush();
      }   
    
    }