Spring MVC interceptor and file upload

Spring MVC interceptor and file upload

Summary

Spring MVC's processor interceptor is similar to the Filter filter in Servlet development, which is used to preprocess and postprocess the processor. Developers can define their own interceptors to implement specific functions.

The difference between filter and Interceptor: interceptor is the concrete application of AOP.

Filter

  • Part of the servlet specification that any java web project can use
  • After / * is configured in URL pattern, all resources to be accessed can be blocked

Interceptor

  • The interceptor is the spring MVC framework's own. Only projects that use the spring MVC framework can use it
  • The interceptor only intercepts the accessed controller methods. If jsp/html/css/image/js is accessed, it will not be intercepted

1. Create a new Moudule
2. Configure the web.xml and springmvc-servlet.xml files
3. Write an interceptor

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    //Execute before the method of request processing
    //If you return true, execute the next interceptor
    //If false is returned, the next interceptor will not be executed
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("------------Before processing------------");
        return true;
    }

    //Execute after request processing method execution
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("------------After treatment------------");
    }

    //It is executed after the dispatcher servlet is processed and cleaned
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("------------Clear------------");
    }
}

4. Configure interceptors in the configuration file of spring MVC

<! -- about interceptor configuration -- >
<mvc:interceptors>
    <mvc:interceptor>
        Include path and its subpath -- >
        <! -- / admin / * what is blocked is / admin/add and so on, / admin/add/user will not be blocked -- >
        <! -- / admin / * * it is all under / admin / >
        <mvc:mapping path="/**"/>
        <! -- the bean configures the interceptor -- >
        <bean class="com.kuang.interceptor.MyInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

5. Write a Controller to receive the request

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//Test the interceptor's controller
@Controller
public class InterceptorController {

    @RequestMapping("/interceptor")
    @ResponseBody
    public String testFunction() {
        System.out.println("The method in the controller performs");
        return "hello";
    }
}

6. Front end index.jsp

<a href="${pageContext.request.contextPath}/interceptor">Interceptor test</a>

Verify user login (authenticated user)

Implementation ideas

  1. There is a landing page. You need to write a controller access page.
  2. The landing page has an action to submit the form. It needs to be processed in the controller. Determine whether the user name and password are correct. If correct, write the user information to the session. Return to login success.
  3. Intercept the user request and judge whether the user logs in. If the user has logged in. Release. If the user does not log in, go to the login page

Code writing

1. Write a login page login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>

<h1>Login page</h1>
<hr>

<body>
<form action="${pageContext.request.contextPath}/user/login">
    User name:<input type="text" name="username"> <br>
    Password: <input type="password" name="pwd"> <br>
    <input type="submit" value="Submission">
</form>
</body>
</html>

2. Write a Controller to handle the request

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    //Jump to landing page
    @RequestMapping("/jumplogin")
    public String jumpLogin() throws Exception {
        return "login";
    }

    //Jump to success page
    @RequestMapping("/jumpSuccess")
    public String jumpSuccess() throws Exception {
        return "success";
    }

    //Landing submission
    @RequestMapping("/login")
    public String login(HttpSession session, String username, String pwd) throws Exception {
        // Record user identity information to session
        System.out.println("Receiver front end==="+username);
        session.setAttribute("user", username);
        return "success";
    }

    //Quit landing
    @RequestMapping("logout")
    public String logout(HttpSession session) throws Exception {
        // session expired
        session.invalidate();
        return "login";
    }
}

3. Write a successful landing page success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>Login success page</h1>
<hr>

${user}
<a href="${pageContext.request.contextPath}/user/logout">Cancellation</a>
</body>
</html>

4. Test the jump on the index page! Start Tomcat test, you can enter the home page without login!

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1>home page</h1>
  <hr>
  <%--Sign in--%>
  <a href="${pageContext.request.contextPath}/user/jumplogin">Sign in</a>
  <a href="${pageContext.request.contextPath}/user/jumpSuccess">Success page</a>
  </body>
</html>

5. Write user login interceptor

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        // Release if landing page
        System.out.println("uri: " + request.getRequestURI());
        if (request.getRequestURI().contains("login")) {
            return true;
        }

        HttpSession session = request.getSession();

        // If the user has logged in, it can also be released
        if(session.getAttribute("user") != null) {
            return true;
        }

        // The user did not log in to jump to the login page
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

6. Register interceptors in the configuration file of spring MVC

<!--On the configuration of interceptors-->
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean id="loginInterceptor" class="com.kuang.interceptor.LoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

7. Restart Tomcat test again!

File upload

Preparation

File upload is one of the most common functions in project development. Spring MVC can support file upload very well, but MultipartResolver is not equipped by default in spring MVC context, so it can't handle file upload by default. If you want to use spring's file upload function, you need to configure MultipartResolver in the context.

Front end form requirements: in order to upload files, you must set the method of the form to POST and the enctype to multipart / form data. Only in this case, the browser will send the file selected by the user to the server as binary data;

Make a detailed description of the enctype attribute in the form:

  • Application / x-www = form urlencoded: by default, only the value in the form field is processed
    Attribute value. The form with this encoding will process the value in the form field into URL encoding.
  • Multipart / form data: this encoding method will process the form data in the way of binary stream. This encoding method will also encapsulate the content of the file specified in the file field into the request parameters, and will not encode the characters
  • text/plain: except for converting spaces to "+" numbers, no other characters are encoded. This method is applicable to sending mail directly through the form.
<form action="" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit">
</form>

Once the enctype is set to multipart / form data, the browser will process the form data in the way of binary stream, and the processing of file upload involves parsing the original HTTP response on the server side. In 2003, the Apache Software Foundation released the open source Commons FileUpload component, which soon became the best choice for Servlet/JSP programmers to upload files.

  • The Servlet 3.0 specification has provided methods to handle file uploads, but such uploads need to be done in the Servlet.
  • Spring MVC provides a simpler package.
  • Spring MVC provides direct support for file upload, which is implemented with plug and play MultipartResolver.
  • Spring MVC uses Apache Commons FileUpload
    Technology implements a MultipartResolver implementation class: CommonsMultipartResolver. Therefore, the spring MVC file upload also needs to rely on Apache
    Components of Commons FileUpload.

File upload

1, Maven will automatically help us import the Commons IO package of the jar package uploaded by the import file;

<!--File upload-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<!--servlet-api Import a higher version of-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

2, Configuration bean: multipartResolver
Attention!!! The bena id must be: multipartResolver, otherwise an error of 400 will be reported when uploading the file! I planted a hole here, lesson! ]

<! -- file upload configuration -- >
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <! -- the encoding format of the request must be consistent with the pageEncoding property of the jSP, so that the contents of the form can be read correctly. The defau lt is iso-8859-1 -- >
    <property name="defaultEncoding" value="utf-8"/>
    <! -- upper limit of upload file size, in bytes (10485760=10M) - >
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>

Common methods of CommonsMultipartFile:

  • String getOriginalFilename(): get the original name of the uploaded file
  • InputStream getInputStream(): get file stream
  • void transferTo(File dest): save the uploaded file to a directory file

Let's actually test it

3, Write front page

<form action="/upload" enctype="multipart/form-data" method="post">
  <input type="file" name="file"/>
  <input type="submit" value="upload">
</form>

4, Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class FileController {
    //@RequestParam("file") encapsulates the file from the name=file control into CommonsMultipartFile object
    //Upload CommonsMultipartFile in batch as an array
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

        //Get file name: file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //If the file name is empty, go back to the home page directly!
        if ("".equals(uploadFileName)){
            return "redirect:/index.jsp";
        }
        System.out.println("Upload file name : "+uploadFileName);

        //Upload path save settings
        String path = request.getServletContext().getRealPath("/upload");
        //If the path does not exist, create a
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("Upload file storage 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";
    }
}

5, Test upload file, OK!

Use file.Transto to save the uploaded file

1 write Controller

/*
 * Use file.Transto to save the uploaded file
 */
@RequestMapping("/upload2")
public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

    //Upload path save settings
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
        realPath.mkdir();
    }
    //Upload file address
    System.out.println("Upload file storage address:"+realPath);

    //Write files directly through CommonsMultipartFile (note this time)
    file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

    return "redirect:/index.jsp";
}

2 front end form submission address modification
3 visit submit test, OK!

File download

File download steps:

  1. Set response response header
  2. Read file – InputStream
  3. Write out file – OutputStream
  4. Execution operation
  5. Close flow (first on then off)

Code implementation:

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

    //1. Set response response header
    response.reset(); //Set page not to cache, clear buffer
    response.setCharacterEncoding("UTF-8"); //Character encoding
    response.setContentType("multipart/form-data"); //Binary transfer data
    //Set 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 file -- output stream
    OutputStream out = response.getOutputStream();

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

Front end

<a href="/download">Click to download</a>

With the help of madness teacher's blog, you can read it if you are interested Crazy about Java

Published 17 original articles, won praise 2, visited 485
Private letter follow

Keywords: Spring JSP Session Java

Added by jbloom on Sat, 07 Mar 2020 13:12:24 +0200