dborba
dborba

Reputation: 643

How can you serve a dynamically generated file w/ Tomcat & Java technology?

Having a hard time figuring out how to send dynamic data to a web-app's user without having to create a file & using a dynamic link to static content using java technology. (The main reasons for avoiding the file creation on disk are security and speed)

This is something I have previously done in python, but this web-app is intended to be strictly java technology for maintenance purposes.

After doing a few searches in google I haven't gotten any further. Has anyone done this before or has a good idea for a starting point?

Upvotes: 1

Views: 2459

Answers (1)

Mercer Traieste
Mercer Traieste

Reputation: 4678

You can output any kind of content type from a servlet. Just set the headers right, and dump to the body of the request the content you want to send.

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + file);
// generate the content and send it to response.getOutputStream()

This will set the content-type to an excel file, and force the browser to download the file.

As a bonus, you can tell your servlet to listen to a specific path, and set the link with a real filename.

<servlet-mapping>
    <servlet-name>Export</servlet-name>
    <url-pattern>/export/*</url-pattern>
</servlet-mapping>

<a href="<%=request.getContextPath()%>/export/Myreport.xls">
    Myreport.xls
</a>

Upvotes: 4

Related Questions