编写拦截器方法
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);
}
}
把拦截器方法给放到我们自定义MVC的配置里面
@Configuration 把我们的配置给加载到容器里面
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor() )
.addPathPatterns("/*")
.excludePathPatterns("/","/login");
}
}
拦截器执行流程
拦截器有一下三种方法
顺序是
先执行 然后执行目标方法 然后是 最后是 如果有多个拦截器的顺序是这样的 先按顺序执行拦截器的preHandle 全部执行完执行目标方法 然后再按照反顺序执行postHandle
文件上传
@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";
}
下面这个分别是收到的单个文件和多个文件 这是文件的储存 先判断文件存不存在 如果存在就用MultipartFile里面的TransFer方法发到文件夹里面
|