I. File Download Overview
For static resources such as slice or HTML, you can download them by opening the correct URL in the browser. The Servlet/JSP Container sends the resource to the browser as long as the resource is placed in the application directory or its subdirectory, but not in the WEB-INF. However, sometimes static resources are stored outside the application directory or in the database, or sometimes you need to control the resources for some people to see, it also prevents other websites from referencing it. In this case, resources must be programmed.
By programming, we can download a file, but we can choose to send it to the browser.
To send resources such as files to a browser, complete the following work in servlet. The following figure shows that JSP pages are generally not used, because the browser will not display the binary code to be sent.
1. Set the response content type to the file content type.
The header Content-Type specifies the data type in the entity body, including the "media type" and "child type identifier ". If you want the browser to always display as the "Save as" dialog box, set the content type to application/octetstream.
2. Add an HTTP response header named content-disposition.
Assign a value to the response header: attachment; filename = "XXX ". Here, XXX is the default file name displayed in the file download dialog box. It can be the same or different from the actual file name.
The following is an example of object download:
response.setContentType(contenttype);FileInputStream fis=new FileInputStream(file);BufferedInputStream bis=new BufferedInputStream(fis);byte[] bytes=new byte[1024];OutputStream os=response.getOutputStream();bis.read(bytes);os.write(bytes);
First, the file to be downloaded is treated as a fileinputstream and the content is added to a byte array;
Obtain the outputstream of httpservletresponse, call its write () method, and pass the byte array to it.
Ii. Download a hidden file instance
In the example below, the secret.pdf file is placed in the WEB-INF/data and cannot be accessed directly. Use a filedownloadservletto send the secret.pdf file to the browser, but the authorized user can browse the file. If the user does not log on, the application will jump to the login interface. Here, the user can enter the user name and password in the form, and the content will be submitted to another loginservlet for processing.
The following figure shows the structure of the application:
1. the user submits the logon form.
The login. jsp page contains an HTML form with two input fields: username and password.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">Loginservlet is called when a form is submitted. Its Class Code is as follows. In this application, I assume that the user name and password must be Ken/secret.
package filedownload;import java.io.IOException;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class LoginServlet */public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString username=request.getParameter("userName");String password=request.getParameter("password");if(username!=null&&username.equals("ken")&&password!=null&&password.equals("secret")){HttpSession session=request.getSession(true);session.setAttribute("loggedIn", Boolean.TRUE);response.sendRedirect("download"); //must call return or else the code after this if //block,if any,will be executed return;}else{RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");dispatcher.forward(request, response);}}}<span style="font-size:14px;"></span>
After a user successfully logs on, A loggedln session attribute is set and the user is transferred to filedownloadservlet.
After httpservletresponse. sendredirect, it must be returned to prevent subsequent code lines from being executed. After logon fails, the user is redirected to the login. jsp page.
2. download the file
Filedownloadservletshows the servlet that is responsible for sending the secret.pdf file. Access is allowed only when the user's httpsession contains the loggedlin attribute, indicating that the user has successfully logged on.
package filedownload;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class FileDownloadServlet */public class FileDownloadServlet extends HttpServlet {private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileDownloadServlet() { super(); // TODO Auto-generated constructor stub }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubHttpSession session=request.getSession();if(session==null||session.getAttribute("loggedIn")==null){RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");dispatcher.forward(request, response);return;//must return after dispatcher.forward(),Otherwise the code below will be executed}String dataDirectory =request.getServletContext().getRealPath("/WEB-INF/data/secret.pdf");//System.out.println(dataDirectory);File file=new File(dataDirectory);if(file.exists()){response.setContentType("application/pdf");response.addHeader("Content-Disposition", "attachment;filename=secret.pdf");byte[] buffer=new byte[1024];FileInputStream fis=null;BufferedInputStream bis=null;try{fis=new FileInputStream(file);bis=new BufferedInputStream(fis);OutputStream os=response.getOutputStream();int i=bis.read(buffer);while(i!=-1){os.write(buffer,0,i);i=bis.read(buffer);}}catch(IOException e){System.out.println(e.toString());}finally{if(bis!=null){bis.close();}if(fis!=null){fis.close();}}}else{System.out.println("secret.pdf does not exit!");}}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}}
The doget method checks whether the loggedin attribute exists in httpsession. If not, the user is taken to the logon page.
HttpSession session=request.getSession();if(session==null||session.getAttribute("loggedIn")==null){RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");dispatcher.forward(request, response);return;//must return after dispatcher.forward(),Otherwise the code below will be executed}
Note that calling forward in requestdispatcher transfers control to different resources. However, it does not stop the code execution of the currently called object. Therefore, it must be returned after the jump.
If the user has successfully logged on, the doget method will open the requested resource and direct it to the outputstream of the servletresponse.
String dataDirectory =request.getServletContext().getRealPath("/WEB-INF/data/secret.pdf");//System.out.println(dataDirectory);File file=new File(dataDirectory);if(file.exists()){response.setContentType("application/pdf");response.addHeader("Content-Disposition", "attachment;filename=secret.pdf");byte[] buffer=new byte[1024];FileInputStream fis=null;BufferedInputStream bis=null;try{fis=new FileInputStream(file);bis=new BufferedInputStream(fis);OutputStream os=response.getOutputStream();int i=bis.read(buffer);while(i!=-1){os.write(buffer,0,i);i=bis.read(buffer);}}catch(IOException e){System.out.println(e.toString());}finally{if(bis!=null){bis.close();}if(fis!=null){fis.close();}}}else{System.out.println("secret.pdf does not exit!");}
Call filedownloadservlet using the following URL to test the application:
http://localhost:8080/app12a/download
3. PS: Web. xml configuration file
<?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"> <display-name>app12a</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>FileDownloadServlet</display-name> <servlet-name>FileDownloadServlet</servlet-name> <servlet-class>filedownload.FileDownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileDownloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>filedownload.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping></web-app>
4. Test
Excerpt from: Servlet and JSP Learning Guide
Servlet Study Notes (9)-File Download