文章目录提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 前言
- 一、自定义一个拦截器类
- 二、引入和使用拦截器
- 1.引入
- 2.使用
- 总结
前言
学会springmvc的拦截器的使用
一、自定义一个拦截器类在springboot同目录下创建一个web目录存放自定义拦截器
创建一个普通类实现HandlerInterceptor,实现方法preHandle。在里面可以自定义拦截的规矩
package com.hello.testspringbootdemo02.web;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class handler implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("chenggongle");
return true;
}
}
二、引入和使用拦截器
1.引入
在和启动类同目录下创建config文件夹存放拦截器实现类
创建普通类实现WebMvcConfigurer接口,实现addInterceptors方法。在里面引用自定义的拦截器和拦截地址和排斥拦截地址
在类上添加configuration注解
package com.hello.testspringbootdemo02.config;
import com.hello.testspringbootdemo02.web.handler;
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 myappconfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
handler had=new handler();
String ok[]={"/user/**"};
String no[]={"/user/login"};
registry.addInterceptor(had).addPathPatterns(ok).excludePathPatterns(no);
}
}
2.使用
和启动类同目录下创建contoller目录,在目录下创建contoller类
package com.hello.testspringbootdemo02.controler;
import com.sun.xml.internal.bind.v2.util.QNameMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class controler_hello {
@ResponseBody
@RequestMapping("/hello")
public String hello()
{
return "hello,nihao";
}
@ResponseBody
@RequestMapping("/hello1")
public String hello1()
{
return "hello,nihao1";
}
@Value("${name}")
private String name;
@ResponseBody
@RequestMapping("/text")
public String text(){
return name;
}
@RequestMapping("/user/login")
@ResponseBody
public String login(){
return "lgin";
}
@RequestMapping("/user/get")
@ResponseBody
public String get(){
return "get";
}
}
启动启动类,游览地址即可显示效果
总结
拦截器



