Spring MVC interceptor and file upload

Learning objectives

1,Interceptor
2,File upload and download
3,RESTFul

1. Interceptor

1.1 interceptor concept

Similar to the Filter filter in Java Web, it is used to Filter requests and intercept requests that do not meet the requirements

Difference between interceptor and filter:

1) Filters are more widely used than interceptors, which can be used by Java Web projects. Interceptors can only be used in spring MVC

2) Interceptor efficiency higher than filter

1.2 use of interceptors

1) Implement the HandlerInterceptor interface

2) Implementation method

  • preHandle preprocessing

  • postHandle post processing

  • afterCompletion post processing

/**
 * Login interceptor
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * Preprocessing
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //Query whether the session saves the user
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            //No login, redirect to login page
            response.sendRedirect("/pages/login");
            //Return false to intercept
            return false;
        }
        //Return true and release
        return true;
    }
}

3) Configure interceptor

	<!--Configuring Interceptors -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--Configure intercepted URL Request path /**Represents all requests -- >
            <mvc:mapping path="/**"/>
            <!--Configure request paths that are not intercepted -- >
            <mvc:exclude-mapping path="/**/login"/>
            <mvc:exclude-mapping path="/**/*.css"/>
            <mvc:exclude-mapping path="/**/*.js"/>
            <mvc:exclude-mapping path="/**/*.png"/>
            <mvc:exclude-mapping path="/**/*.jpg"/>
            <!--to configure class-->
            <bean class="com.blb.bookms.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

2. File upload and download

2.1 file upload

There are two ways to upload files:

  • Traditional Servlet file upload

  • Spring MVC file upload

2.1.1 traditional Servlet file upload

1) Import dependency

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

2) Write form

Three elements of form file upload:

  1. Add enctype = "multipart / form data" to the form tag
  2. The submission method is post
  3. The input type is file
<form  action="/upload" method="post" enctype="multipart/form-data">
    ...
    <input type="file" name="file" >
    ...
</form>

2) Upload method

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String fileupload(HttpServletRequest request) throws Exception {
        //Get the upload directory path of the project
        String path= request.getSession().getServletContext().getRealPath("/upload/");
        File file=new File(path);
        //Determine whether the folder exists
        if (!file.exists()){
            //create folder
            file.mkdirs();
        }
        //Create upload object
        ServletFileUpload upload=new ServletFileUpload(new DiskFileItemFactory());
        //Get file list
        List<FileItem> fileItems= upload.parseRequest(request);
        for (FileItem item:fileItems){
            //Determine whether the file is an ordinary form item
            if (item.isFormField()){
                //If it is a normal form item, print the form item name and value
                System.out.println(item.getFieldName());
                System.out.println(item.getString());
            }else{
                //If it is a file, intercept the suffix
                String filename= item.getName();
                String suffix = filename.substring(filename.lastIndexOf("."));
                //Create a unique file name
                String uuid= UUID.randomUUID().toString().replace("-","");
                filename = uuid + suffix;
                //Complete file upload
                item.write(new File(path,filename));
                System.out.println("Upload complete");
            }
        }
        //Jump to success page
        return "success";
    }

2.1.2 spring MVC file upload

The dependency form is the same as above

The MultipartFile parameter is used in the upload method to obtain the uploaded file

@RequestMapping("/upload")
public String fileupload(HttpServletRequest request, MultipartFile upload) throws Exception {
    //Get the upload directory path under the project directory
    String path = request.getSession().getServletContext().getRealPath("/upload/");
    System.out.println(path);
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }
    //Get the name of the uploaded file
    String filename = upload.getOriginalFilename();
    String suffix = filename.substring(filename.lastIndexOf("."));
    //Create a unique file name
    String uuid= UUID.randomUUID().toString().replace("-","");
    filename = uuid + suffix;
    //Complete file upload
    upload.transferTo(new File(path,filename));
    return "success";
}

You need to add an upload processor to the spring MVC configuration

<!--Upload processor-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
    <!--Maximum bytes of uploaded file-->
    <property name="maxUploadSize" value="10485760"/>
</bean>

2.1.3 spring MVC multi file upload

Add multiple file items to the form

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

Add MultipartFile array as parameter, and the parameter name is consistent with the form name

@RequestMapping("/upload3")
public String fileupload3(HttpServletRequest request, MultipartFile[] uploads) throws Exception {
    //Get the upload directory path under the tomcat project directory
    String path = request.getSession().getServletContext().getRealPath("/upload/");
    System.out.println(path);
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }
    for(MultipartFile upload : uploads) {
        //Get the name of the uploaded file
        String filename = upload.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        //Create a unique file name
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "-" + suffix;
        //Complete file upload
        upload.transferTo(new File(path, filename));
    }
    return "success";
}

2.1.4 other upload classes of spring MVC

Spring MVC also provides other API s to support uploading:

  • CommonsMultipartResolver multipart resolver is used to determine whether there is an uploaded file in the request
  • MultipartHttpServletRequest is a multipart request used to obtain file related information

Specific usage:

@RequestMapping("upload4")
public String  fileupload4(HttpServletRequest request) throws IllegalStateException, IOException
{
    String path = request.getSession().getServletContext().getRealPath("/upload/");
    //Create multipart parser
    CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
            request.getSession().getServletContext());
    //Check whether the form supports file upload
    if(multipartResolver.isMultipart(request)){
        //Convert the request into multi part request and support uploading
        MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
        //Gets all the file names in the request
        Iterator iter=multiRequest.getFileNames();
        while(iter.hasNext()) {
            //Traverse all files
            MultipartFile file=multiRequest.getFile(iter.next().toString());
            if(file!=null) {
                //Get the name of the uploaded file
                String filename = file.getOriginalFilename();
                String suffix = filename.substring(filename.lastIndexOf("."));
                //Create a unique file name
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid + suffix;
                //upload
                file.transferTo(new File(path,filename));
            }
        }
    }
    return "success";
}

2.2 file download

/**
 * Download controller
 */
@Controller
public class DownloadController {

    @RequestMapping("download")
    public void download(String file,  HttpServletResponse response) throws IOException {
        //Path to download file
        String path = "D:\\install\\";
        File downFile = new File(path+file);
        if(downFile.exists()){
            //Set browser download content type, response header
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition","attachment;filename="+file);
            //Send files by streaming
            Files.copy(downFile.toPath(),response.getOutputStream());
        }
    }
}

3,RestFul

3.1 front and rear end separation

3.1.1 what is the front and rear end separation

Front end projects (html5, applet, mobile terminal) and back-end projects (java, database, tomcat) are developed and deployed separately

3.1.2 front and rear end separation advantages

1) The development division of labor is clear, and the front-end team and back-end team work together at the same time

2) The project deploys different servers separately. For example, Tomcat is suitable for deploying dynamic resources and Nginx is suitable for deploying static resources

3) Easy to test and maintain

3.1.3 interaction mode of front and rear end developers

1) Designers design interfaces according to requirements and provide interface documents

1) The back-end develops the background interface according to the interface document

2) The front end requests data through the interface and renders the page

3.2 RESTFul

3.2.1 what is restful

RESTFul is a design style and development method of network applications. It is based on HTTP and can be defined in XML format or JSON format. It is applicable to the scenario where the mobile Internet manufacturer acts as a service enabling interface to realize the function of a third party calling mobile network resources. The action types are adding, changing and deleting the called resources.

RESTful architecture is the most popular Internet software architecture. It has clear structure, conforms to standards, is easy to understand and easy to expand, so it is being adopted by more and more websites.

3.2.2 characteristics of restful architecture

  1. Each URI corresponds to a resource (database data, method, etc.) on the server

  2. Add, delete, modify and query operations are distinguished through different Http request methods

  • Get -- > query

  • Post -- > Add

  • Put -- > Update

  • Delete -- > delete

  1. The format of communication is JSON

3.2.3 RESTFul style API

In traditional API design, verbs are often used to define APIs, such as find, get, save, update, delete, etc

Query all books:
http://Domain name / book/findAll
 Query a Book:
http://Domain name / book/findById?id=1
 Add books:
http://Domain name / book/saveBook
 Update books:
http://Domain name / book/updateBook
 Delete book:
http://Domain name / book/deleteBook?id=1

RESTFul style API design uses only nouns and different request methods to distinguish addition, deletion, modification and query

Query all books: 	GET
http://Domain name / books
 Query a Book:		GET
http://Domain name / book/1
 Add books:		POST
http://Domain name / book
 Update books:		PUT
http://Domain name / book
 Delete book:		DELETE
http://Domain name / book/1

Implementation of Restful style controller

@RestController defines a RestFul style controller, in which all methods directly return data, which is equivalent to adding @ ResponseBody

@RestController
public class BookController {

    @Autowired
    private BookService bookService;
    
    @GetMapping("/books")
    public JsonResult findAll(){
        try {
            List<Book> list = bookService.list();
            return new JsonResult(1,list);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }
    
    @GetMapping("/book/{id}")
    public JsonResult findById(@PathVariable("id")Integer id){
        try {
            Book book = bookService.getById(id);
            return new JsonResult(1,book);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }


    @PostMapping("/book")
    public JsonResult saveBook(@RequestBody Book book){
        try {
            bookService.save(book);
            return new JsonResult(1,null);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }


    @PutMapping("/book")
    public JsonResult updateBook(@RequestBody Book book){
        try {
            bookService.updateById(book);
            return new JsonResult(1,null);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }


    @DeleteMapping("/book/{id}")
    public JsonResult delBook(@PathVariable("id")Integer id){
        try {
            bookService.removeById(id);
            return new JsonResult(1,null);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }
}

3.2.4 the browser supports DELETE and PUT

By default, the browser only supports GET and POST requests. If you want the form to submit DELETE or PUT requests, you need to implement it through the spring MVC filter

web.xml add:

<filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

HiddenHttpMethodFilter is used to filter the form named_ The hidden field of method. If the value is DELETE, the request method will be converted to DELETE, and if it is PUT, the request method will be converted to PUT.

form

<form action="/testDelete" method="post">
    <input name="name" placeholder="Enter name"><br>
    <input type="hidden" name="_method" value="DELETE"/>
    <input type="submit" value="Submit">
</form>

Tags: Back-end RESTful

Posted on Wed, 27 Oct 2021 02:16:39 -0400 by joaca