web Common Object 02

Keywords: Session Tomcat Attribute encoding

Session

Effect
Identify a session, or confirm a user, and share data during a session (multiple requests from a user).
Obtain
The request.getSession() method creates objects without sessions, or obtains session objects for the current session.
Method
getId() - Get the session identifier
getCreationTime() - Get the creation time
getLastAccessedTime() - Get the last access time
isNew() - Determine whether a new session is available
As a domain object
Session is used to represent a session in which data can be shared.
Add data to the domain object by setAttribute(name,value); method
Getting data from domain objects by getAttribute(name)
Remove data from domain objects by removeAttribute(name).
Destruction
1. Default expiration time
The default lifetime of session in Tomcat is 30 minutes, that is, when you do not operate the interface, session will be re-timed once it is operated. Modifications can be made in the web.xml file in Tomcat.
  < session-config>
  < session-timeout>30< /session-timeout>
  < /session-config>
2. Set your own deadline
Set the session life cycle by session.setMaxInactiveInterval(int); set the maximum inactivity time of the session in seconds. Use getMaxInactiveInterval(); method to see the maximum inactivity time of the current session object.
3. Destroy session
  session.invalidate();
4. Close the browser
The bottom layer of session is dependent on cookie s, and the default browser shutdown is invalid.
5. Close the server
Abnormal shutdown of server
Note: If the server is normally shut down by stop, session objects will be passivated to the local disk. When the server is abnormally shut down, session will be destroyed. When the server is shut down normally, session will be serialized to the disk and SESSION in the workspace work directory. In the. ser file, the next time the service is started, it is automatically loaded into memory.

ServletContext

Get the ServletContext object:
1) Obtain by request
    request.getServletContext()
2) Getting through session
    request.getSession().getServletContext()
3) Through getServletConfig method
    getServletConfig().getServletContext()
4) Direct access
    getServletContext()
common method
getServerInfo() - Get server version information
getRealPath("/") - Get the path of the project in the server
As a domain object
By accessing data to ServletContext, the whole application can share some data.

File upload and download

File upload
Reception:
1. The form submission type is POST, and the form type is enctype= "multipart/form-data"
2. Setting the name attribute value of form elements

 <form	action="uploadServlet" method="post" enctype="multipart/form-data">
	 	//Documents:<input type="file" name="myfile" />
	 	<button>Submission</button>
</form>

Backstage:
First, you need to import third-party jar packages. http://commons.apache.org/ Download resources for commons-io and commons-fileupload jars. Unzip and import into the project. commons-fileupload.jar is the core package of file upload, commons-io.jar is the dependency package of file upload, and is also a toolkit.
DiskFile ItemFactory - Set disk space and save temporary files. Just a tool class
ServletFileUpload - The core class of file upload, which receives request s and parses them
ServletFileUpload.parseRequest(request); - List parses request
1. Create a DiskFileItemFactory class and make temporary files and sizes
2. Create ServletFileUpload Core Class, Receive Temporary Files, Make Request Conversion
3. Transform the original request through the ServletFileUpload class to get the FileItem collection
4. Traverse the elements in the set and process them
5. Determine whether each element is a regular form item or not, and if so, treat it as a regular form item.
6. If it is not an ordinary form item, it is a document, which is processed (uploaded)

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Set the encoding format of the request
		request.setCharacterEncoding("UTF-8");
		
		// Get the path of upload directory under tomcat
		String path = getServletContext().getRealPath("/upload");
		// Temporary File Directory
		String tempPath = getServletContext().getRealPath("/temp");
		
		// 1. Declare the DiskFileItemFactory factory class to set up a temporary directory on the specified disk
		DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
		// 2. Declare ServletFileUpload and receive the temporary files above. Default values can also be used
		ServletFileUpload up = new ServletFileUpload(disk);
		try {
			// // 3. parsing request
			List<FileItem> list = up.parseRequest(request);
			if (list.size() > 0) {
				// Traversing form items
				for (FileItem file : list)
					// Determine whether it is a normal form item
					if (file.isFormField()) {
						String fieldName = file.getFieldName(); // name attribute value of form element
						// Chinese scramble code, at this time also need to specify the encoding method of data acquisition
						// String value = file.getString();
						String value = file.getString("UTF-8"); // The value of the text box
						System.out.println(fieldName + "=" + value);
					} else { // The note is a document.
						// Get the name of the file itself
						String fileName = file.getName(); // Get the uploaded file name
						System.out.println(file.getFieldName());
						// Processing File Name (Intercepting\ Symbols, etc.)
						fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
						System.out.println("old Name : " + fileName);
						// Modify the name (get the suffix name of the file)
						String extName = fileName.substring(fileName.lastIndexOf("."));
						// Generate random characters, stitch file suffixes, stitch new file names
						String newName = UUID.randomUUID().toString().replace("-", "") + extName;
						// Save the new name and write it to the new file
						file.write(new File(path + "/" + newName));
						System.out.println("The file name is:" + fileName);
						System.out.println("The file size is:" + file.getSize());
						file.delete(); // Delete temporary files
					}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

File Download
Hyperlink Download
When the hyperlink href is an unrecognized resource of the browser, it will be downloaded automatically.
Setting the download attribute requires the browser to download.
Download in the background
1) The HttpServletResponse.setContentType method is needed to set the value of the Content-type header field for MIME types that browsers cannot process in some way or activate a program, such as "application/octet-stream" or "application/x-msdownload".
2) You need to set the value of Content-Disposition header as "attachment;filename = filename" through the HttpServletResponse.setHeader method.
3) Read the download file and call the OutputStream object returned by the HttpServletResponse.getOutputStream method to write the attachment content to the client.
Reception

<form action="downloadServlet" method="post">
		//File name:<input type="text" name="fileName" /> <button>download</button>
</form>

Backstage

public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Set the encoding format of the request
		request.setCharacterEncoding("UTF-8");
		// Get the file name to download
		String fileName = request.getParameter("fileName");
		// Get the storage path of the file (the path where the project is stored in the server)
		String realPath = request.getServletContext().getRealPath("/upload/");
		// File path
		String filePath = realPath + fileName;
		// Get the file object through the path
		File file = new File(filePath);
		// Determine whether a file exists
		if (file.exists()) {
			// MIME types that browsers cannot handle in some way or activate a program
			response.setContentType("application/x-msdownload");
			// Setting Content-Disposition Header
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			// Get the input stream of the file
			InputStream in = new FileInputStream(file);
			// Get the output stream
			ServletOutputStream out = response.getOutputStream();
			// output stream
			byte[] bytes = new byte[1024];
			int len = 0;
			while((len = in.read(bytes)) != -1) {
				out.write(bytes, 0, len);
			}
			// Closing flow
			out.close();
			in.close();
		} else {
			System.out.println("The file does not exist. Please try again.!");
		}
		
		
	}

}

Posted by benjudy on Tue, 13 Aug 2019 02:37:54 -0700