How to use SpringBoot's HandlerInterceptor interceptor

1. Create an interceptor

Create the interceptor you want to use by implementing the HandlerInterceptor interface

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
     */
    @Override
    public 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
     */
    @Override
    public 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{}代码块  总是执行    无论请求正确或出现异常都会进入该方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("==========3=============");
    }
}

The preHandle method is executed before the Http request is executed.

The postHandle method is executed after executing the method of the request path.

The afterCompletion method is executed after all Http requests are completed.

This is the method of Http request path

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 {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private 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);
    }
}

2. Register the interceptor into 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 {
    @Autowired
    private LoginTicketInterceptor loginTicketInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginTicketInterceptor);
    }
}

3. Test results

 

Guess you like

Origin blog.csdn.net/weixin_55127182/article/details/132688429