2011-01-07 51 views
41

我編寫了使用REST JAX-RS生成Excel文件的代碼,並且確認生成的Excel文件位於GlassFish服務器目錄中。如何在JAX-RS中設置響應頭,以便用戶可以看到Excel的下載彈出窗口?

但我的目標是當用戶點擊按鈕(生成Excel .xls)時,我想要下載彈出窗口來顯示詢問用戶是否要保存或打開.xls文件,就像任何其他Web服務一樣,文件類型。

根據我的搜索中,步驟是:

  1. 生成的Excel的.xls(DONE)

  2. 寫Excel以流

  3. 在JAX-RS文件

    ,設定響應標題類似,

    String fileName =「Blah_Report.xls」; response.setHeader(「Content-Disposition」,「attachment; filename =」+ fileName);

我的問題是我在JAX-RS文件中做了所有這些,而我沒有HttpServletResponse對象可用。

Add Response Header to JAX-RS Webservice

回答他說:

你可以在你的web服務 注入通過 @Context註釋的參考 HttpServletResponse的實際使用和的addHeader()等。添加您的 標題。

我真的不能弄清楚到底是什麼意思,而不樣本代碼..

回答

73

您不需要HttpServletResponse來設置響應頭。您可以使用 javax.ws.rs.core.Response。只是讓你的方法,而不是返回實體的響應:

return Response.ok(entity).header("Content-Disposition", "attachment; filename=" + fileName).build() 

如果你仍然想使用HttpServletResponse的,你可以得到它要麼注入類的領域之一,或使用性質,或者方法參數:

@Path("/resource") 
class MyResource { 

    // one way to get HttpServletResponse 
    @Context 
    private HttpServletResponse anotherServletResponse; 

    // another way 
    Response myMethod(@Context HttpServletResponse servletResponse) { 
     // ... code 
    } 
} 
+0

@GarretWilson爲什麼不呢?什麼讓你困惑?這是一個簡單的標題。 – Tarlog 2014-12-25 15:02:29

+0

因爲單例MyResource會同時由多個線程調用myMethod()。每個線程都有不同的`HttpServletResponse`實例,但單獨的`anotherServletResponse`成員變量一次只能保存一個值。唯一的方法是,如果`anotherServletResponse`被注入了一些使用線程本地或某些線程安全的代理來確定當前線程的實際`HttpServletResponse`實例。 – 2014-12-25 15:16:24

0

我想通設置HTTP響應頭和流通過在標準的servlet瀏覽器顯示下載彈出。注意:我正在使用Excella,excel輸出API。

package local.test.servlet; 

import java.io.IOException; 
import java.net.URL; 
import java.net.URLDecoder; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import local.test.jaxrs.ExcellaTestResource; 
import org.apache.poi.ss.usermodel.Workbook; 
import org.bbreak.excella.core.BookData; 
import org.bbreak.excella.core.exception.ExportException; 
import org.bbreak.excella.reports.exporter.ExcelExporter; 
import org.bbreak.excella.reports.exporter.ReportBookExporter; 
import org.bbreak.excella.reports.model.ConvertConfiguration; 
import org.bbreak.excella.reports.model.ReportBook; 
import org.bbreak.excella.reports.model.ReportSheet; 
import org.bbreak.excella.reports.processor.ReportProcessor; 

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"}) 
public class ExcelServlet extends HttpServlet { 

    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 


     try { 

      URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls"); 
      // /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls 
      System.out.println(templateFileUrl.getPath()); 
      String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); 
      String outputFileDir = "MasatoExcelHorizontalOutput"; 

      ReportProcessor reportProcessor = new ReportProcessor(); 
      ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); 

      ReportSheet outputSheet = new ReportSheet("MySheet"); 
      outputBook.addReportSheet(outputSheet); 

      reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); 
      System.out.println("wtf???"); 
      reportProcessor.process(outputBook); 


      System.out.println("done!!"); 
     } 
     catch(Exception e) { 
      System.out.println(e); 
     } 

    } //end doGet() 

    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    } 

}//end class 



class OutputStreamExporter extends ReportBookExporter { 

    private HttpServletResponse response; 

    public OutputStreamExporter(HttpServletResponse response) { 
     this.response = response; 
    } 

    @Override 
    public String getExtention() { 
     return null; 
    } 

    @Override 
    public String getFormatType() { 
     return ExcelExporter.FORMAT_TYPE; 
    } 

    @Override 
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { 

     System.out.println(book.getFirstVisibleTab()); 
     System.out.println(book.getSheetName(0)); 

     //TODO write to stream 
     try { 
      response.setContentType("application/vnd.ms-excel"); 
      response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); 
      book.write(response.getOutputStream()); 
      response.getOutputStream().close(); 
      System.out.println("booya!!"); 
     } 
     catch(Exception e) { 
      System.out.println(e); 
     } 
    } 
}//end class 
14
@Context ServletContext ctx; 
@Context private HttpServletResponse response; 

@GET 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
@Path("/download/{filename}") 
public StreamingOutput download(@PathParam("filename") String fileName) throws Exception { 
    final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName); 
    response.setHeader("Content-Length", String.valueOf(file.length())); 
    response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\""); 
    return new StreamingOutput() { 
     @Override 
     public void write(OutputStream output) throws IOException, 
       WebApplicationException { 
      Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output)); 
     } 
    }; 
} 
相關問題