0
我有一個名爲export.jsp的網頁,當用戶訪問domain/export.jsp時,我希望他通過servlet的doGet方法自動下載csv文件。後來我想,以顯示實際的JSP文件,該文件export.jsp如何在顯示jsp頁面之前觸發doGet
我doGet方法如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//RequestDispatcher rd = request.getRequestDispatcher("/export.jsp");
//rd.forward(request, response);
//getting and loading the property file
Properties propConfig = new Properties();
Properties propLog = new Properties();
Statement stmt = null;
Connection connection = null;
try {
//Loading the property files
propConfig.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties"));
propLog.load(getServletContext().getResourceAsStream("/WEB-INF/log4j.properties"));
PropertyConfigurator.configure(propLog);
logger.info("loaded log4j properties From Path: /WEB-INF/log4j.properties");
connection = DbTools.getConnection(propConfig.getProperty("db_hostname"),
propConfig.getProperty("db_port"), propConfig.getProperty("db_serviceName"),
propConfig.getProperty("db_userName"),propConfig.getProperty("db_password"));
stmt = connection.createStatement();
ResultSet rset = stmt .executeQuery("SELECT * FROM QACOMPLETE_DEFECT");
File csvfile = FileTools.generateCsvFile(rset);
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "inline; filename=\""+csvfile.getName()+"\"");
OutputStream outputStream = response.getOutputStream();
outputStream.write(Files.readAllBytes(Paths.get(csvfile.getAbsolutePath())));
outputStream.flush();
outputStream.close();
} catch (SQLException e) {
logger.error("SQLException", e);
}catch (IOException e) {
logger.error("IOexception, The user may have cancel the download ", e);
}
finally
{
DbTools.closeQuietly(stmt);
DbTools.closeQuietly(connection);
}
}
我的web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<description></description>
<display-name>DefectExporter</display-name>
<servlet-name>DefectExporter</servlet-name>
<servlet-class>exporter.DefectExporter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DefectExporter</servlet-name>
<url-pattern>/export.jsp</url-pattern>
</servlet-mapping>
</web-app>
上午我做錯了什麼?因爲當我在瀏覽器中輸入url http://localhost:7001/DefectsExporter/export.jsp
時,會觸發doGet方法,但不會顯示網頁export.jsp。
首先,你的servlet不會轉發到JSP(它的兩條線被註釋掉了)。但即使這樣做,您已將servlet映射到JSP的URL,因此轉發將再次調用該servlet。將servlet映射到**另一個** URL,並轉發到doGet()中的JSP。但是,再次,由於您的servlet已經將CSV發送給響應,所以您也無法以相同的響應發送HTML。所以,實際上,你應該告訴我們你想要做什麼,因爲目前這沒什麼意義。 –
感謝您的迴應,也許我應該重新配置:我希望能夠下載一次鏈接的csv文件:http:// localhost:7001/DefectsExporter/export.jsp在瀏覽器中輸入,一旦執行下載,我想顯示實際的jsp頁面 – coldistric