Spring MVC interceptor and file upload

Learning objectives 1,Interceptor 2,File upload and download 3,RESTFul 1. Interceptor ...
1.1 interceptor concept
2.1 file upload
2.1.1 traditional Servlet file upload
2.1.2 spring MVC file upload
2.1.3 spring MVC multi file upload
2.1.4 other upload classes of spring MVC
2.2 file download
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/> </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 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

27 October 2021, 02:16 | Views: 4101

Add new comment

For adding a comment, please log in
or create account

0 comments