1. The HttpSession object

1.1 Functions and Object Creation

The purpose of a Session is to identify a Session, or a user; And share data during a session (multiple requests from a user). We can get the session object of the current session using the request.getSession() method

HttpSession session=request.getSession();
Copy the code

1.2 Identifying the Session JSESSIONID

Since the function of a Session is to identify a Session, the Session should have a unique identifier, which is the sessionId.

Each time a request arrives at the server, if a session is opened (the session is accessed), the server first checks whether a cookie named JSESSIONID is returned from the client. If not, the server considers it a new session. A new session object is created and the session is marked with a unique sessionId. If the cookie with the JSESSIONID is returned, the server will check whether there is a session object with the JSESSION value based on the JSESSIONID value. If there is no session object, the server will consider it as a new session and create a new session Object and marks the session; If the corresponding session object is found, it is considered to be a previously flagged session, and the session object is returned. The data is shared.

There is a cookie called JSESSIONID. This is a special cookie. When a user requests a session, the server will create a JSESSIONID with a value of get Cookie object of session (whether obtained or newly created), and added to the response object, the response to the client, valid time to close the browser.

So the underlying Session implementation relies on cookies.

1.3 Session Domain Objects

Session identifies a session in which data can be shared. In this case, the session exists as a domain object

You can use session.setAttribute(name,value) to add data to a domain object

Get data from the domain object using session.getAttribute(name)

Use session.removeAttribute(name) to remove data from the domain object.

Ex. :

HttpSession session=request.getSession(); session.setAttribute("name","Tom"); response.sendRedirect("servletdemo"); // Because the data in a session is shared, the data in the session is still valid with redirectionCopy the code

Whether the request is forwarded or redirected, the data in the session scope remains valid for the entire session.

1.4 Session destruction

  1. By default, the session object is automatically destroyed if no operation is performed on the server within the specified time

  2. I set a time pass the session. SetMaxInactiveInterval (int) to set the session one of the biggest inactivity time, units are seconds

Through the session. The getMaxInactiveInterval (int) to obtain the maximum inactivity time session

  1. Disable the browser session since the underlying cookie; The browser is invalid when closed by default

  2. Closing the server When the server is abnormally shut down, the session is closed

5. Manually destroy session.invalidate();

2. The ServletContext object

2.1 introduction

Each Webb Application has only one ServletContext object, also known as the Application object, which is related to the Application from its name. When the Web container is started, a corresponding ServletContext object is created for each Web application.

This object has two functions. One is used as a domain object for data sharing, in which the data is shared across the application. This object holds information about the current application.

For example, the getServerInfo() method is used to get the current server information. Get a resource as a stream using the getResourceAsStream(String Path) method; Use getRealPath(String Path) to obtain the real path of the resource

2.2 Obtaining the ServletContext Object

There are several ways to get the ServletContext object:

  1. Through the request object:

    ServletContext servletContext=request.getServletContext();

  2. Through the session

    ServletContext servletContext=request.getSession().getServletContext();

  3. Through the ServletConfig

    ServletContext servletContext=getServletConfig().getServletContext();

  4. Direct access to

    ServletContext servletContext=getServletContext();

2.3 As a Domain object

A ServletContext can also be used as a domain object, allowing the entire application to share data in it by storing it. However, it is recommended not to store too much, because the data in the ServletContext will always exist unless manually removed.

Ex. :

ServletContext servletContext=getServletContext();
servletContext.setAttribute("name1","value1");
servletContext.getAttribute("name1");
servletContext.removeAttribute("name1");
Copy the code

3. Download files

3.1 Hyperlink download

Hyperlinks are automatically downloaded when they encounter dynamic web pages that the browser doesn’t recognize. When the browser encounters a recognized resource, it will display it by default, such as TXT, PNG, JPG. We can also specify the browser to download via the Download attribute.

Ex. :

<a href="upload/abc.zib">Copy the code

Specify the Download attribute to download:

<a href="upload/abc.txt" download>Copy the code

Download can not write any information, will automatically use the default file name. So when the user opens the browser and clicks on the link, the file will be downloaded directly

3.2 Background Download

Implementation steps:

1. Need through the HttpServletResponse. SetContentType method to set the value of the content-type header field, MIME types that cannot be processed by the browser or activated by a program, such as "application/octet-stream" or "application/x-msdownload" 2. Need through the HttpServletResponse. SetHeader methods set the Content - Disposition has a value of "legislation; Filename = filename "3. Read the download file, call the HttpServletResponse. GetOutputStream () method returns the OutputStream object to the client in the attachment content.Copy the code

Code:

public class DownloadServlet extends HttpServlet{ protected void service (HttpServletRequest request,HttpServletResponse  response) throws ServletException,IOException{ request.setCharacterEncoding("UTF-8"); String Path =getServletContext().getrealPath ("/")+"download/"; String filename=request.getParameter("filename"); File file=new File(path+filename); If (file.exists()){// Set the response type. Application /x-msdownload Response.setContentType ("application/x-msdownload"); Response. setHeader(" content-disposition ","attachment; filename="+filename); InputStream is = new FileInputStream(file); ServletOutputStream os = resp.getOutputStream(); byte[] car = new byte[1024]; int len = 0; while ((len = is.read(car)) ! = -1) { os.write(car, 0, len); } // Close the stream and release the resource os.close(); is.close(); } else {system.out.println (" file does not exist, download failed!" ); }}}}Copy the code