【问题标题】:URL should not contain Servlet name after exporting导出后 URL 不应包含 Servlet 名称
【发布时间】:2018-12-12 06:56:33
【问题描述】:
public class ExcelWriter extends HttpServlet{
    private void writeExcel(List<Book> listBook, String excelFilePath)
            throws IOException {
        Workbook workbook = getWorkbook(excelFilePath);
        Sheet sheet = workbook.createSheet();

        int rowCount = 0;

        for (Book aBook : listBook) {
            Row row = sheet.createRow(++rowCount);
            writeBook(aBook, row);
        }

        try (FileOutputStream outputStream = new FileOutputStream(new File(
                excelFilePath))) {
            workbook.write(outputStream);
        }
    }

    private void writeBook(Book aBook, Row row) {
        Cell cell = row.createCell(1);
        cell.setCellValue(aBook.getTitle());

        cell = row.createCell(2);
        cell.setCellValue(aBook.getAuthor());

        cell = row.createCell(3);
        cell.setCellValue(aBook.getPrice());
    }

    private List<Book> getListBook() {
        Book book1 = new Book("Head  Java", "Anot Serria", 79);
        Book book2 = new Book("Effective Java 1", "Bnot Bloch", 36);
        Book book3 = new Book("Clean Code 1", "Cnot Martin", 42);
        Book book4 = new Book("Thinking in Java 2", "D Eckel", 35);

        List<Book> listBook = Arrays.asList(book1, book2, book3, book4);

        return listBook;
    }

    private Workbook getWorkbook(String excelFilePath) throws IOException {
        Workbook workbook = null;

        if (excelFilePath.endsWith("xlsx")) {
            workbook = new XSSFWorkbook();
        } else if (excelFilePath.endsWith("xls")) {
            workbook = new HSSFWorkbook();
        } else {
            throw new IllegalArgumentException(
                    "The specified file is not Excel file");
        }

        return workbook;

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            ExcelWriter excelWriter = new ExcelWriter();
            List<Book> listBook = excelWriter.getListBook();
            String excelFilePath = "C:\\ExcelTemp\\Temp.xls";
             excelWriter.writeExcel(listBook, excelFilePath);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
  • 下载 excel 文件后,Servlet 应将我指向初始视图页面,即从哪里导出数据。我不想将其转发到正在使用的同一页面。

    功能应该就像我从 index.html--&gt;ExcelWriter Servlet 导出数据一样。但 url 不应该显示 Servlet 部分。请帮帮我。我正在使用 Apache POI 和 Servlet。我还有一本带有 getter 和 setter 方法的 POJO 姓名簿。

【问题讨论】:

    标签: java html servlets apache-poi


    【解决方案1】:

    您可以在 web 描述符文件(xml 文件)中进行 servlet 映射。

    【讨论】:

    • Servlet 映射由我完成,导出后我想要相同的 index.html。它不应该转到 url 中的 SERVLET NAME
    • 在这种情况下进行 AJAX 调用。这将是一个异步调用,因此 url 不会被更改。
    猜你喜欢
    • 2012-05-16
    • 2011-08-31
    • 2022-06-25
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多