【学习笔记】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
文件并实现WebMvcConfigurer
的addInterceptors
。
@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 //多文件