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";
    }
}
相关推荐
Narutolxy2 分钟前
深入探讨 Go 中的高级表单验证与翻译:Gin 与 Validator 的实践之道20241223
开发语言·golang·gin
Hello.Reader9 分钟前
全面解析 Golang Gin 框架
开发语言·golang·gin
禁默20 分钟前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程
Cachel wood27 分钟前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架
Code哈哈笑29 分钟前
【Java 学习】深度剖析Java多态:从向上转型到向下转型,解锁动态绑定的奥秘,让代码更优雅灵活
java·开发语言·学习
gb421528732 分钟前
springboot中Jackson库和jsonpath库的区别和联系。
java·spring boot·后端
程序猿进阶33 分钟前
深入解析 Spring WebFlux:原理与应用
java·开发语言·后端·spring·面试·架构·springboot
qq_4336184435 分钟前
shell 编程(二)
开发语言·bash·shell
zfoo-framework40 分钟前
【jenkins插件】
java