Thursday, July 7, 2011

Struts 2 Gzip HTML Output

I want to send back gzip file of an html file.


struts.xml:



<action name="ReportView" class="ReportViewAction" method="execute">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">fileStream</param>
        <param name="bufferSize">1024</param>
    </result>
</action>


Note:  you can set/override this static params in your action by providing getters.  For example, to return a dynamic value for the contentType


public String getContentType() {
   // contentType is set to whatever you want
   // depending on your content.
   // be it text/html, application/vnd.ms-excel, application/pdf
   return contentType;  
}


Action:



public class ReportViewAction extends ActionSupport implements ServletResponseAware {

    private String id;
    private InputStream fileStream;
    
    @Override
     public String execute() throws Exception {
         Session session = HibernateUtil.currentSession(false);
         Report report = (Report)session.load(Report.class, id);
         // content is a Blob
         fileStream = report.getContent().getBinaryStream();
         return super.execute();
    }
     
     public String getId() {
         return id;
     }

     public void setId(String id) {
         this.id = id;
     }

     // this matches the inputName specified struts.xml
     public InputStream getFileStream() {
         return fileStream;
     }

     public void setFileStream(InputStream fileStream) {
         this.fileStream = fileStream;
     }

     @Override
     public void setServletResponse(HttpServletResponse response) {
         response.setHeader("Content-Encoding", "gzip");
     }
}



No comments:

Post a Comment