java spring boot 拦截器

1 创建拦截器

java 复制代码
package com.example.demo212;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.hutool.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //String token = request.getHeader("token");
        //if (!StringUtils.hasText(token)){
            //没有token,说明没有登录
            //使用response设置响应给前端的信息,根据自己的业务需求
            //return false;
        //}
        //验证token的合法性,根据自己的业务逻辑补充
        //return true;

        if (request.getSession().getAttribute("user") == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                JSONObject res = new JSONObject();
                res.put("success", false);
                res.put("message", "用户未登录!");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2 写拦截器配置

java 复制代码
package com.example.demo212;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器
        InterceptorRegistration ir = registry.addInterceptor(new MyInterceptor());
        // 添加拦截请求
        ir.addPathPatterns("/*");
        // 添加不拦截的请求
        ir.excludePathPatterns("/login");

        // 以上三句代码可以使用下面的代替
        // registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*").excludePathPatterns("/login");
    }
}

3.测试类

java 复制代码
package com.example.demo212;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.*;


@SpringBootApplication
@RestController
@Validated
public class Demo212Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo212Application.class, args);
    }
    @RequestMapping("/getUser")
    public String getUserStr(String name, Integer age) {
        return "name: " + name + " ,age:" + age;
    }
    @GetMapping("/login")
    public String Login(){
        return "login";
    }

    @GetMapping("/add")
    public String add(){
        return "add";
    }
}
相关推荐
皮皮林5517 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河7 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程10 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅12 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者13 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺13 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart14 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP15 小时前
MyBatis-mybatis入门与增删改查
java
孟陬18 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端