【学习笔记】SpringBoot拦截器和文件上传

【学习笔记】SpringBoot拦截器和文件上传

在这里插入图片描述

拦截器

拦截器的概念

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

作用:

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

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


拦截器的配置

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


//必须实现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 文件并实现WebMvcConfigureraddInterceptors

@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中我们就不在过多介绍,原理其实都差不多。

前端文件:

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

Controller层的配置:

@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 //多文件

在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铁甲小宝同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值