1. The interceptor

1.1 Interceptors and filters

SpringMVC’s processor interceptor is similar to the Filter used in Servlet development to preprocess and postprocess the processor. We can customize some interceptors to implement specific functions

The difference between filters and interceptors: Interceptors are concrete applications of AOP ideas

Filter:

  • Part of the Servlet specification that can be used by any JavaWeb project
  • After /* is configured in url-pattern, all resources to be accessed can be intercepted

The interceptor:

  • Interceptors are the SpringMVC framework’s own and can only be used by projects that use the SpringMVC framework
  • The interceptor directs the controller method to intercept access, not JSP/HTML/CSS /img/js

1.2 Custom interceptors

  1. Start by writing a class that implements the HandlerInterceptor interface

    public class MyInterceptor implements HandlerInterceptor {
        
        /** * is called before the request is processed by the business handler * If false is returned * afterCompletion() of all interceptors is executed back from the current interceptor, and then exits the interceptor chain * If true * The next interceptor is executed until all interceptors have completed * Execute the intercepted Controller * then enter the interceptor chain, * execute all postHandle() back from the last interceptor * then execute all afterCompletion() back from the last interceptor */
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
            System.out.println("------------ before processing ------------");
            return true;
        }
     
        /** * Actions performed before the view is generated * can add data to modelAndView, such as the current time */ after the business processor completes the execution of the request
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("------------ after processing ------------");
        }
     
        /** * is called after the DispatcherServlet has fully processed the request and can be used to clean up resources, etc. ** afterCompletion() of all interceptors will be executed back from the current interceptor when an exception is thrown
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception ex) throws Exception {
            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- to clean up -- -- -- -- -- -- -- -- -- -- -- --"); }}Copy the code
  2. Configure interceptors in the SpringMVC configuration file

    <! -- Interceptor configuration -->
    <mvc:interceptors>
        <mvc:interceptor>
            <! --/** includes paths and their subpaths -->
            <! /admin/add/user /admin/add/user
            <! --/admin/** intercepts all files under /admin/
            <mvc:mapping path="/ * *"/>
            <! The interceptor is configured for the bean.
            <bean class="com.kuang.interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    Copy the code

2. Upload and download files

2.1 upload

  1. First, the encType attribute in the form must be set to multipart/form-data. Only in this way can the form data be processed in binary stream mode. This encoding-mode encapsulates the contents of the file specified by the file field into the request parameters, and does not encode characters.

    • Application/X-www =form-urlencoded: Default, only value attribute values in forms are processed. Forms that use this encoding method will process the values in form fields as URL-coded
    • Text /plain: Handles the conversion of Spaces to ‘+‘, other characters are not encoded
  2. Then import the associated JAR package, Commons-Fileupload

  3. Configuration bean: **multipartResolver

    <! -- file upload configuration, id must be multipartResolver-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <! The request must be in the same format as the pageEncoding property of the jSP in order to read the form correctly. The default is ISO-8859-1.
        <property name="defaultEncoding" value="utf-8"/>
        <! -- Maximum size of uploaded files, in bytes (10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
    Copy the code
  4. CommonsMultipartFile

    • **String getOriginalFilename() : ** Gets the original name of the uploaded file
    • **InputStream getInputStream() : ** Gets the file stream
    • **void transferTo(File dest) : ** Saves the uploaded File to a directory File
  5. Writing Controller

    @Controller
    public class FileController {
        // @requestParam ("file") encapsulates the name=file file into the CommonsMultipartFile object
        // Upload CommonsMultipartFile as an array
        @RequestMapping("/upload")
        public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
     
            // Get the file name: file.getoriginalfilename ();
            String uploadFileName = file.getOriginalFilename();
     
            // If the file name is empty, go back to the home page!
            if ("".equals(uploadFileName)){
                return "redirect:/index.jsp";
            }
            System.out.println("Upload filename:"+uploadFileName);
     
            // Upload path save Settings
            String path = request.getServletContext().getRealPath("/upload");
            // If the path does not exist, create one
            File realPath = new File(path);
            if(! realPath.exists()){ realPath.mkdir(); } System.out.println("Upload file save address:"+realPath);
     
            InputStream is = file.getInputStream(); // File input stream
            OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); // File output stream
     
            // Read write
            int len=0;
            byte[] buffer = new byte[1024];
            while((len=is.read(buffer))! = -1){
                os.write(buffer,0,len);
                os.flush();
            }
            os.close();
            is.close();
            return "redirect:/index.jsp"; }}Copy the code
  6. Or use file.transto to upload files

    @RequestMapping("/upload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    
        // Upload path save Settings
        String path = request.getServletContext().getRealPath("/upload");
        // Upload file address
        File realPath = new File(path);
        if(! realPath.exists()){ realPath.mkdir(); }// Write the file directly via CommonsMultipartFile (note this time)
        file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
    
        return "redirect:/index.jsp";
    }
    Copy the code

2.2 download

File download steps:

  1. Set response response header
  2. Read file -> InputStream
  3. Write out the file -> OutputStream
  4. Perform operations
  5. Close the stream

Code implementation:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
    // The address of the image to download
    String  path = request.getServletContext().getRealPath("/upload");
    String  fileName = "Basic grammar.jpg";

    // set the response header
    response.reset(); // Set the page to no cache and clear the buffer
    response.setCharacterEncoding("UTF-8"); // Character encoding
    response.setContentType("multipart/form-data"); // Binary data transfer
    // Set the response header
    response.setHeader("Content-Disposition"."attachment; fileName="+URLEncoder.encode(fileName, "UTF-8"));

    File file = new File(path,fileName);
    //2, read file -- input stream
    InputStream input=new FileInputStream(file);
    //3, write out the file -- output stream
    OutputStream out = response.getOutputStream();

    byte[] buff =new byte[1024];
    int index=0;
    // perform write operations
    while((index= input.read(buff))! = -1){
        out.write(buff, 0, index);
        out.flush();
    }
    out.close();
    input.close();
    return null;
}
Copy the code