springboot拦截器使用

首页 / 🍁编程类 / 正文

springboot我准备分俩版本来使用,俩版本区别不是很大

  1. 第一个版本只是单纯的实现拦截器功能
  2. 第二个版本在拦截器功能上面实现跳转功能,也就是拦截成功的基础上完成跳转

公共部分

SpringbootLanjieqiApplication启动类

@SpringBootApplication
public class SpringbootLanjieqiApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootLanjieqiApplication.class, args);
    }
}

LoginInterceptor声明类

public class LoginInterceptor  implements HandlerInterceptor {

    //只是创建是拦截器,还需调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("测试拦截器是否生效");
        return true;
    }
}

MyConfig拦截器注册类

@Configuration
public class MyConfig  implements WebMvcConfigurer {

    //添加拦截对象
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor interceptor=new LoginInterceptor();

        //指定拦截的url地址
        String [] Path={"/xiaonan/**"};

        //不拦截的url地址
        String [] excludePath={"/xiaonan/login"};
        registry.addInterceptor(interceptor).addPathPatterns(Path).excludePathPatterns(excludePath);

    }
}

上面是公共部分

版本一

如果只是单纯了解拦截器用法,那就把下面注释的代码放开,把现在放开的代码注释掉,即可,这样就不会报错了

@Controller
public class ControllerClass {

    @ResponseBody
    //@RequestMapping("xiaonan/user")
    public String xiaonanUser(){
        //return "拦截xiaonan/user地址";
        return "error";
    }
    @RequestMapping("xiaonan/login")
    //@ResponseBody
    public String xiaonanLogin(){
        //return "不拦截xiaonan/login地址";
        return "success";
    }

}

版本二

在原有的基础上面增加了,视图解析器,也就是跳转功能,也是上面的代码,直接复制就行了。但是增加了application.properties文件的使用

需要添加试图解析器了就修改下这个文件

spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html

添加之后,并且要在pom.xml文件里面添加。

当然这个不是必须的,如果不使用这个会很麻烦,所以我选择简单的,直接使用模板引擎来操作

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

修改完成和添加完成之后,自己手动创建处error和login的html文件即可
文章全部是本人原创,请勿转发,谢谢配合,版权所有-南香香-你会喜欢我吗

评论区
头像