一、创建拦截器
通过实现HandlerInterceptor接口创建自己要使用的拦截器
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Configuration
public class LoginTicketInterceptor implements HandlerInterceptor {/*** preHandle最先执行的方法* @param request 请求* @param response 响应* @param handler 当前请求请求的控制器方法对象 DemoController#demo* @return* @throws Exception*/@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("==========1=============");return true;}/**** @param request* @param response* @param handler 当前请求请求的控制器方法对象 DemoController#demo* @param modelAndView 模型和视图 当前请求访问方法的modelandview对象* @throws Exception*/@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("==========2=============");}/**** @param request* @param response* @param handler 当前请求请求的控制器方法对象 DemoController#demo* @param ex 如果控制器出现异常时异常对象* @throws Exception* 这个方法相当于:try{}catch{}finally{}中的finally{}代码块 总是执行 无论请求正确或出现异常都会进入该方法*/@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("==========3=============");}
}
其中preHandle方法是Http请求执行之前去执行的
其中postHandle方法是执行请求路径的方法后去执行的
其中afterCompletion方法是所有Http请求完成后去执行的
这个是Http请求路径的方法
import com.springboot3.domain.Course;
import com.springboot3.domain.DataTime;
import com.springboot3.mapper.CourseMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;@RequestMapping("/course")
@RestController
@CrossOrigin
@Slf4j
public class CourseController {@Autowiredprivate RedissonClient redissonClient;@Autowiredprivate CourseMapper courseMapper;@Autowiredprivate RedisTemplate redisTemplate;@GetMapping("/test/{id}")public ConcurrentHashMap<String, DataTime> test(@PathVariable("id")String id, HttpServletResponse response) {ConcurrentHashMap<String, DataTime> treeMap = new ConcurrentHashMap<>();RLock lock = null;try {Object courseRedis = redisTemplate.opsForValue().get(id);lock = redissonClient.getLock("CourseLock");lock.lock();if (courseRedis == null) {Course course = courseMapper.selectById(id);redisTemplate.opsForValue().set(course.getId(),course);dateTime(id, treeMap);}else{dateTime(id, treeMap);}} catch (Exception e) {throw new RuntimeException(e);} finally {lock.unlock();}Cookie cookie=new Cookie("ticket","ticket");cookie.setMaxAge(3600*2);response.addCookie(cookie);System.out.println("正在执行Course接口");return treeMap;}private void dateTime(String id, ConcurrentHashMap<String, DataTime> treeMap) {DataTime dataTime = new DataTime();dataTime.setData(redisTemplate.opsForValue().get(id));dataTime.setTime(LocalDateTime.now());treeMap.put("dataTime",dataTime);}
}
二、将拦截器注册到Spring中
package com.springboot3.config;import com.springboot3.interceptor.LoginTicketInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate LoginTicketInterceptor loginTicketInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginTicketInterceptor);}
}
三、测试结果