severlet uploads a single file
Use the annotation @MultipartConfig to identify each Servlet as supporting file upload
Servlet encapsulates the POST request of multipart/form-data into a Part object, and operates the uploaded file through Part.
Common methods
public Collection
// Used to get all the request headers contained in this part of the data
public String getHeader(String name)
//Used to obtain a single value corresponding to the specified field name from the request header contained in this part of the data
public Collection
//Used to obtain all values corresponding to the specified field name from the request header contained in this part of the data
public String getName()
//Used to get the name of the form component corresponding to this part of the data
public String getSubmittedFileName()
//Used to get the original name of the file uploaded by the user
public long getSize()
//Used to get the size of the text data in this part of the data. For file upload operations, it is to get the size of the uploaded file.
public String getContentType()
//The MIME type used to obtain the text data in this part of the data, corresponding to the content-type field in the request header
public void write(String fileName) throws IOException
//Used to write the text data in this part of the data to the specified file. For file upload operations, it means writing the file content to the specified file.
public void delete() throws IOException
//Used to delete the cache file corresponding to this part of the data
public InputStream getInputStream() throws IOException
//This method is used to return a byte input stream, through which the text data in this part of the data can be read
A collection of field names
To upload a file, you need to set the enctype attribute of the form to multipart/form-data. At this time, the content-type in the request header when sending a network request is multipart/form-data. This content type will convert the data submitted by the request into multiple segments. Spliced in the form of (each form item is a segment), and then sent to the server in the form of a binary stream.
Upload a single file
<form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" multiple> <input type="submit" value="Upload multiple files"> </form>
?
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Upload a file req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); Part file = req.getPart("file"); String submittedFileName = file.getSubmittedFileName(); //Get the uploaded file name String name = submittedFileName; ? String dir = "E:\load"; submittedFileName = dir + File.separator + submittedFileName; File file1 = new File(submittedFileName); if (!file1.getParentFile().exists()){ file1.getParentFile().mkdirs(); } try{ file.write(submittedFileName); //Write to the default path String s = "<a href='/download?file=" + submittedFileName + "' >Download picture</a>"; resp.getWriter().write(s); //Output to the page System.out.println("File uploaded successfully"); }catch (IOException e){ e.printStackTrace(); System.out.println("Failed to upload file"); } }
Upload multiple files
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Upload multiple files String remoteAddr = req.getRemoteAddr(); if ("0:0:0:0:0:0:0:1".equals(remoteAddr)){ remoteAddr = "127.0.0.1"; } resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); Collection<Part> parts = req.getParts(); String link = ""; String message = ""; for (Part part:parts) { String contentType = part.getContentType(); //Get the format of the image String fileName = part.getSubmittedFileName(); //Get file name if (Constant.ALLOW_TYPES.contains(contentType)){ File file = new File(Constant.UPLOAD_PATH + File.separator + fileName); if (!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } part.write(fileName); String s = "<a href=http://10.0.3.149/download?file=" + fileName + ">Download" + fileName.substring(0,fileName.lastIndexOf(".")) + "</a>"; link + = s + "</br>"; message + = "<p>" + fileName + "Upload successful</p>"; FilesDao filesDao = new FilesDao(); try { boolean insert = filesDao.insert(remoteAddr,fileName.substring(0,fileName.lastIndexOf(".")),contentType,file.length(),Constant.getTime(file.lastModified()),s); if (insert){ System.out.println("Database upload successful:" + fileName); }else { System.out.println("Failed to upload database:" + fileName); } } catch (SQLException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }else{ message + = "<p>" + fileName + "Upload failed, file format is not supported</p>"; } } String html = "<html><body>"; html + = message; html + = "<p>The download address is as follows:</p>"; html + = link; html + = "</body></html>"; resp.getWriter().write(html); ? }else { System.out.println("Please log in again"); resp.sendRedirect(req.getContextPath() + "/error.html"); } } ?
Download a single file
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Download a file resp.setContentType("application/octet-stream"); //Binary stream download String file = req.getParameter("file"); //Get the value of the name attribute defined when uploading file resp.setHeader("Content-disposition","attachment;filename=" + file); String path = Constant.UPLOAD_PATH + File.separator + file; ServletOutputStream outputStream = resp.getOutputStream(); //Get the corresponding output stream (binary) FileInputStream fileInputStream = new FileInputStream(path); fileInputStream.transferTo(outputStream); fileInputStream.close(); outputStream.close(); }
Conversation
The user opens the browser, accesses the resources of the web server, and the session is established until one party disconnects and the session ends. A session can contain multiple requests and responses
Session Tracking
A method of maintaining browser state. The server needs to identify whether multiple requests come from the same browser in order to share data between multiple requests in the same session. The HTTP
protocol is stateless, each time When the browser makes a request to the server, the server will treat the request as a new request, so we need session tracking technology to achieve intra-session data sharing.
Implementation
-
Client session tracking technology: Cookies
-
Server-side session tracking technology: Session
Cookie
Send Cookie
1. Create Cookie object and set data
Cookie cookie = new Cookie("key","value");
2. Send Cookie to client: use response object
response.addCookie(cookie);
Get Cookie
3. Get all cookies carried by the client and use the request object
Cookie[] cookies = request.getCookies();
4. Get all cookies carried by the client and use the request object
for loop
5. Use Cookie object method to obtain data
cookie.getName(); cookie.getValue();
6. Set cookie survival time
By default, cookies are stored in browser memory. When the browser is closed and the memory is released, the cookie is destroyed.
cookie.setMaxAge(int seconds)//Set the survival time and store it on the hard drive where the browser is located
Positive number: Write the cookie to the hard drive of the computer where the browser is located for persistent storage. Automatically delete when the time expires. Negative number: Default value. The cookie is in the current browser memory. When the browser is closed, the cookie is destroyed. Zero: Delete the corresponding cookie.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Send Cookie //Create Cookie object Cookie cookie=new Cookie("username","zs"); //Set survival time: one minute cookie.setMaxAge(60); //Send Cookie.response response.addCookie(cookie); }
Store Chinese
Cookies cannot store Chinese directly. If they need to be stored, they need to be transcoded: URL encoding.
//Send Cookie protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Send Cookie //Create Cookie object String value="Zhang San"; //URL encoding value= URLEncoder.encode(value,"UTF-8"); Cookie cookie=new Cookie("username",value); //Set survival time: one minute cookie.setMaxAge(60); //Send Cookie.response response.addCookie(cookie); }
//Get Cookie protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get cookies //Get Cookie array Cookie[] cookies = request.getCookies(); //Iterate through the array for (Cookie cookie : cookies) { //retrieve data String name = cookie.getName(); if("username".equals(name)){ String value = cookie.getValue(); //URL decoding value = URLDecoder.decode(value, "UTF-8"); System.out.println(name + ":" + value); } } }
Session
1. Get the Session object
HttpSession session = request.getSession();
2. Session object function
void setAttribute(String name, Object o)//Storage data into the session domain Object getAttribute(String name) //Get the value based on key void removeAttribute(String name) //Delete the key-value pair based on key
//Request 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Stored into Session //Get Session object HttpSession session=request.getSession(); //Storing data session.setAttribute("username","zs"); }
//Request 2 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get data from Session //Get Session object HttpSession session=request.getSession(); //retrieve data Object username = session.getAttribute("username"); System.out.println(username); }
Session passivation and activation
-
Passivation: After the server is shut down normally, Tomcat will automatically write the Session data to a file on the hard disk.
-
Activation: After starting the server again, load data from the file into the Session
The underlying principle: Session is implemented based on Cookie
Seesion destroyed
By default, no operation, automatic destruction in 30 minutes (in web.xml)
<web-app> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
Call the invalidate() method of the Session object (destroy itself)
//Destroy session.invalidate();
The difference between Cookie and Session
Storage location: Cookie stores data on the client, and Session stores data on the server. Security: Cookie is not safe, and Session is safe. Data size: Cookie has a maximum of 3KB, and Session has no size limit. Storage time: Cookie can be stored for a long time, and Session defaults to 30 Minute server performance: Cookies do not occupy server resources, and Sessions occupy server resources.
Three-tier architecture
Three-tier architecture is to divide the entire business application into:
-
User Interface layer UI
-
Business Logic Layer BLL
-
Data Access layer DAL
Presentation layer The presentation layer, also known as the interface layer, is the interface for interacting with users. Located at the outermost/top layer, closest to the user, it is used to receive data input by the user and display the data the user needs after processing.
[Accept the request, encapsulate the data, call the business logic layer, and respond to the data (servlet, jsp)]
Business Logic Layer The business logic layer, also known as the service layer, is the bridge between the presentation layer and the data access layer. Located in the middle layer, it is used to process business logic, including: verification, calculation, business rules, etc. Data access layer The data access layer is the layer that accesses the database. Located at the innermost/lowest level, it mainly implements the addition, deletion, modification and query of data. Submit the data stored in the database to the business layer, and save the data processed by the business layer to the database. The relationship between layers: the presentation layer depends on the business logic layer, and the business logic layer depends on the data access layer
Entity (entity layer): It does not belong to any of the three layers, but it is an essential layer. The role of Entity in the three-layer architecture: 1. Implement object-oriented thinking “Encapsulation”; 2. It runs through the three layers and transmits data between the three layers; (Note: To be precise, the entity layer runs through the three layers to connect the three layers) 3. Each layer (UI-> The data transfer (one-way) between BLL->DAL is passed by variables or entities as parameters, thus constructing the connection between the three layers and completing the realization of the function.
The emergence of the three-tier architecture is for “high cohesion and low coupling”
Cohesion: The degree of relatedness of various elements within a module. Coupling: the degree of association between various modules. High cohesion: As much as possible, a class/module is only responsible for one function (the easier it is to understand, modify and maintain the elements within a module, the fewer errors there will be). Low coupling: The correlation between modules should be as low as possible to avoid affecting the whole body. From a class perspective: High cohesion and low coupling: Reduce the number of calls to other classes within the class. From the functional block perspective : High cohesion and low coupling: reduce the complexity of interactions between modules