ResourceMapping Spring MVC

It is pretty easy to create a Resource handler using Spring Portlet MVC
Portlet needs resource URL to create download links for PDF/CSV etc.

Steps,

1.<a href="<portlet:resourceURL escapeXml="false" id="exportAsTxt"/>>Download File </a>

2. Create a controller
@Controller
@RequestMapping("VIEW")
public class ReportController{

}

3.Write a Resource handling method. Add the annotation @ResourceMapping

@ResourceMapping(value = "exportAsTxt")
public void serveFile(ResourceRequest request, ResourceResponse response) {
response.setProperty("Content-Disposition","attachment; filename=report.txt");
response.setContentType("text/plain");
try {
response.getWriter().write("Save to File");
} catch (IOException e) {
e.printStackTrace();
}
}

To the ResourceResponse set the Content-Disposition property to set the file name
and set the ContentType. The above method is for text file. Similar approach can be followed for PDF/CSV etc.


If any portlet interceptors are configured for the application make sure that the method preHandleResource returns 'true',( incase of an empty implementation ) .

@Override
public boolean preHandleResource(ResourceRequest request,
ResourceResponse response, Object handler) throws Exception {
return true;
}

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I have implemented this as I need a document portlet that gets it's the document from a content management system, but I want to be able to protect the resource, sadly in Liferay 6 ee it does not seem to protect the resource url and force login. Have you had any experience with this?

    ReplyDelete