好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java全面深入探究SpringBoot拦截器与文件上传

拦截器

拦截器的概念

动态拦截Actioon调用的对象,使开发者在一个Actioon执行的前后执行一段代码,也可以在Action执行前阻止其执行,同时也提供了一种可以提取Action中可重用部分代码的方式。

作用:

动态拦截Action调用的对象(也就是实际项目中的controller层的接口)

一般拦截器用于对用户访问的限制。如当用户没有登录时访问主页面,则可以使用拦截器进行拦截并重定向到登录页面。

拦截器的配置

创建interceptor 文件夹并创建LoginInterceptor Java文件且实现HandlerInterceptor 这个接口。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

//必须实现HandlerInterceptor这个接口

public class LoginInterceptor implements HandlerInterceptor {

     /*

     * 目标方法执行以前

     * */

     @Override

     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

         HttpSession session = request.getSession();

         Object loginUser = session.getAttribute( "loginUser" );

         if (loginUser != null ) {

             return true ;

         }

         request.setAttribute( "msg" , "请登录!" );

//        response.sendRedirect("/");

         request.getRequestDispatcher( "/" ).forward(request,response);

         return   false ;

     }

     //目标方法执行以后

     @Override

     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

     }

     /**

      * 页面渲染以后

      * @param request

      * @param response

      * @param handler

      * @param ex

      * @throws Exception

      */

     @Override

     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

         HandlerInterceptor. super .afterCompletion(request, response, handler, ex);

     }

}

配置拦截器

创建 config 文件夹并创建 AdminWebConfig 文件并实现WebMvcConfigurer的addInterceptors。

?

1

2

3

4

5

6

7

8

9

@Configuration

public class AdminWebConfig implements WebMvcConfigurer {

     @Override

     public void addInterceptors(InterceptorRegistry registry) {

         registry.addInterceptor( new LoginInterceptor())

                 .addPathPatterns( "/**" ) //静态路径也会被拦截

                 .excludePathPatterns( "/" , "/login" , "/css/**" , "/fonts/**" , "/images/**" , "/js/**" );

     }

}

拦截器的原理

1、根据当前请求,找到**HandlerExecutionChain【**可以处理请求的handler以及handler的所有 拦截器】

2、先来顺序执行 所有拦截器的 preHandle方法

1、如果当前拦截器prehandler返回为true。则执行下一个拦截器的preHandle 2、如果当前拦截器返回为false。直接 倒序执行所有已经执行了的拦截器的 afterCompletion;

3、如果任何一个拦截器返回false。直接跳出不执行目标方法

4、所有拦截器都返回True。执行目标方法

5、倒序执行所有拦截器的postHandle方法。

6、前面的步骤有任何异常都会直接倒序触发 afterCompletion

7、页面成功渲染完成以后,也会倒序触发 afterCompletion

文件上传

在之前我们学习SSM的时候就知道了 文件上传 这个功能,所以在 SpringBoot中我们就不在过多介绍,原理其实都差不多。

前端文件:

?

1

2

3

4

< form method = "post" action = "/upload" enctype = "multipart/form-data" >

     < input type = "file" name = "file" >< br >

     < input type = "submit" value = "提交" >

</ form >

Controller层的配置:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

@Controller

public class FileController {

     @GetMapping ( "/updateFile" )

     public String FileUp(){

         return "FileUp" ;

     } 

@PostMapping ( "/upload" ) // //new annotation since 4.3

     public String singleFileUpload( @RequestParam ( "file" ) MultipartFile file,

                                    RedirectAttributes redirectAttributes) {

         if (file.isEmpty()) {

             redirectAttributes.addFlashAttribute( "message" , "Please select a file to upload" );

             return "redirect:uploadStatus" ;

         }

         try {

             // Get the file and save it somewhere

             byte [] bytes = file.getBytes();

             Path path = Paths.get( file.getOriginalFilename());

             Files.write(path, bytes);

             redirectAttributes.addFlashAttribute( "message" ,

                     "You successfully uploaded '" + file.getOriginalFilename() + "'" );

         } catch (IOException e) {

             e.printStackTrace();

         }

         return "redirect:/main.html" ;

     }

}

更改文件上传大小

在application.properties中配置文件大小:

spring.servlet.multipart.max-file-size=10MB //单文件大小
spring.servlet.multipart.max-request-size=100MB //多文件

到此这篇关于Java全面深入探究SpringBoot拦截器与文件上传的文章就介绍到这了,更多相关Java SpringBoot拦截器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/m0_54355125/article/details/124694558

查看更多关于Java全面深入探究SpringBoot拦截器与文件上传的详细内容...

  阅读:23次