Fork me on GitHub

SpringBoot———自定义拦截器实现

SpringBoot———自定义拦截器实现

编写拦截器实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package net.zzqd.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration//声明这是一个配置
public class MyInterceptor extends WebMvcConfigurerAdapter {

@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor inter = new HandlerInterceptor()
{

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {

}

@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {

}

@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("自定义拦截器");
return true;
}

};
registry.addInterceptor(inter).addPathPatterns("/**");
}

}

说明:

1、preHandle 方法会在请求处理之前进行调用(Controller方法调用之前)

2、postHandle 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)

3、afterCompletion 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)

在controller业务层,所有地址都会被拦截
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package net.zzqd.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController

public class SpringController {

@RequestMapping("/hello")
//返回的Restful内容,不使用该注解会进行跳转
// @ResponseBody
public String yes()
{
return "hello";
}
@RequestMapping("/ok")
// @ResponseBody
public String ok()
{
return "ok";
}

//支持Rest风格
@RequestMapping("/info/{msg}")
public String show(@PathVariable String msg )
{
return "show"+msg;
}
}
运行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package net.zzqd.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import net.zzqd.controller.SpringController;

//@EnableAutoConfiguration
//@ComponentScan("net.zzqd.controller")
//默认情况下扫描的是当前包以及当前包的子包
@SpringBootApplication(scanBasePackages= {"net.zzqd.controller","net.zzqd.interceptor"})//组合注解
public class SpringApplications {
public static void main(String[] args)
{
SpringApplication.run(SpringApplications.class, args);
}
}