/* set required headers */ response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=DownloadFile.csv"); /* stream the file into a byte array */ byte[] downloadFile = buildDownloadFile(); /* write directly to the client */ OutputStream os = response.getOutputStream(); os.write(downloadFile, 0, downloadFile.length); os.flush(); os.close();
Showing posts with label webapp. Show all posts
Showing posts with label webapp. Show all posts
Java: file download
One way to create a downloadable file in a Java webapp
Simple filter in a Java webapp
Define a filter in web.xml:
<filter>
<filter-name>SimpleFilter</filter-name>
<display-name>SimpleFilter</display-name>
<description>log filter</description>
<filter-class>com.filtertest.SimpleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SimpleFilter</filter-name>
<servlet-name>simple</servlet-name>
<!-- <url-pattern>/request.go</url-pattern>-->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Make sure the FORWARD dispatcher is defined, otherwise only the original request URL will be used to determine if the filter should be invoked. In other words, if FORWARD is missing, any HTTP requests that were forwarded to this resource will not invoke the filter.
Implement a doFilter(…) method in the
com.filtertest.SimpleFilter
class as follows:log.info("Filter invoked"); // pass the request along the filter chain chain.doFilter(request, response); }
Subscribe to:
Posts (Atom)