Article directory
Writing interceptor methods
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;
}else{
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
Put the interceptor method in our custom MVC configuration
@Configuration loads our configuration into the container
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor() )
.addPathPatterns("/*")
//这是要拦截什么路径要用/* 用/**的话静态资源也会被拦截住
.excludePathPatterns("/","/login");
//↑这个是放行那些访问路径
}
}
Interceptor execution flow
There are three methods of interceptor
the order is
First execute,
then execute the target method
, then
finally,
if there are multiple interceptors, the order is like this
First execute the preHandle of the interceptor in order, execute all the target methods,
and then execute the postHandle in reverse order
File Upload
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
log.info("上传的信息:email={},username={},headerImg={},photos={}",
email,username,headerImg.getSize(),photos.length);
if(!headerImg.isEmpty()){
String name = headerImg.getOriginalFilename();
headerImg.transferTo(new File("C:\\Users\\hp\\Desktop\\test\\"+name));
}
if(photos.length>0){
for (MultipartFile photo : photos) {
if(photo!=null){
String name = photo.getOriginalFilename();
photo.transferTo(new File("C:\\Users\\hp\\Desktop\\test\\"+name));
}
}
}
return "main";
}
The following are the received single file and multiple files.
This is the storage of the file. First determine whether the file exists or not.
If it exists, use the TransFer method in MultipartFile to send it to the folder.