當前位置:
首頁 > 知識 > Filter,攔截器,aop攔截的實現與區別

Filter,攔截器,aop攔截的實現與區別

效果

Filter,攔截器,aop攔截的實現與區別

打開今日頭條,查看更多精彩圖片

實現

1 Filter

直接實現Filter介面,重寫攔截方法,再到@WebFilter註解上配置攔截規則即可實現

@Component

@WebFilter(urlPatterns = { "/**" }, filterName = "tokenAuthorFilter")

public class ConfigurationFilter implements Filter{

@Override

public void destroy() {

// TODO Auto-generated method stub

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

// TODO Auto-generated method stub

System.out.println("我是Filter,我攔截到了請求");

chain.doFilter(request, response);//到下一個鏈

}

@Override

public void init(FilterConfig arg0) throws ServletException {

// TODO Auto-generated method stub

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

攔截器

和filter類似 實現HandlerInterceptor介面並重寫攔截方法

public class MyInterceptor implements HandlerInterceptor{

//在請求處理之前進行調用(Controller方法調用之前

@Override

public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

System.out.printf("我是攔截器:preHandle被調用");

HandlerMethod handlerMethod = (HandlerMethod) o;

Method method = handlerMethod.getMethod();

if (method.getAnnotation(interceptorLog.class) != null) {

return true;

}else{

return false;

}

}

//請求處理之後進行調用,但是在視圖被渲染之前(Controller方法調用之後)

@Override

public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

System.out.println("我是攔截器:postHandle被調用");

}

//在整個請求結束之後被調用,也就是在DispatcherServlet 渲染了對應的視圖之後執行(主要是用於進行資源清理工作)

@Override

public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

System.out.println("我是攔截器:afterCompletion被調用");

}

}

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

像spring容器內將創建的攔截器註冊進去

@Configuration

public class interceptorConfig extends WebMvcConfigurerAdapter{

public void addInterceptors(InterceptorRegistry registry){

registry.addInterceptor(new MyInterceptor()) //指定攔截器類

.addPathPatterns("/**"); //指定該類攔截的url

}

}

1

2

3

4

5

6

7

8

自定義一個註解用於攔截標識

@Retention(RetentionPolicy.RUNTIME) // 表示註解在運行時依然存在

@Target(ElementType.METHOD)

@Documented

public @interface interceptorLog {

}

1

2

3

4

5

6

7

aop攔截

pom

<!--AOP-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-aop</artifactId>

</dependency>

<!--druid -->

1

2

3

4

5

6

配置aop

@Component

@Aspect

public class HttpAspect {

@Pointcut("execution(* spring.controller..*.*(..)) && @annotation(spring.annotation.aopLog)")

// @Pointcut("public * *(..)")

public void log(){

}

@Around("log()")

public void aroundLogCalls(JoinPoint joinPoint) throws Throwable {

System.out.println("我是aop:方法環繞start.....");

System.out.println("我是aop:方法環繞end.....");

}

/**

* 列印請求的ur l method ip 類方法 參數

* @param joinPoint

*/

@Before("log()")

public void doBefore(JoinPoint joinPoint){

ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

HttpServletRequest request =attributes.getRequest();

System.out.println("我是aop:方法開始");

}

// @After("execution(public * com.tg.controller.GirlController.*(..))")

@After("log()")

public void doAfter(){

System.out.println("我是aop:方法結束");

}

/**

* 列印請求的具體內容

* @param objects

*/

@AfterReturning(returning = "objects",pointcut = "log()")

public void doAfterReturning(Objects objects){

}

@AfterThrowing("log()")

public void cathInfo(){

System.out.println("異常信息");

}

}

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

43

44

45

46

47

48

49

50

51

52

53

自定義註解用於攔截標識

@Retention(RetentionPolicy.RUNTIME) // 表示註解在運行時依然存在

@Target(ElementType.METHOD)

@Documented

public @interface aopLog {

}

1

2

3

4

5

6

7

被請求方法

@RequestMapping(value = "/userInfo", method = RequestMethod.GET)

@ApiOperation("登錄")

@ResponseBody

@aopLog

@interceptorLog

public Map<String, Object> login(

@RequestParam(value="useName", required=true) String useName,

@RequestParam(value="passWord", required=true) String passWord

){

Map<String,Object> result=new HashMap<String,Object>();

try{

//查詢

userInfo selectedUser= dao.selectUserInfo(useName);

//更新

dao.updateFrequency(useName);

if(selectedUser.getPassWord().equals(passWord)){

result.put("userInfo", selectedUser);

result.put("code", "200");

}else{

result.put("msg", "賬號密碼錯誤");

}

}catch(Exception e){

result.put("code", "404");

}

return result;

}

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

總結:

這是swagger連接到伺服器所觸發的攔截信息,可以看到所有的請求都會被filter首先攔截,並可以預處理request,

而攔截器可以調用IOC容器中的各種依賴,filter就不能獲取註解信息並攔截,因為它和框架無關,但攔截器不能修改request,filter基於回調函數,我們需要實現的filter介面中doFilter方法就是回調函數,而interceptor則基於java本身的反射機制,而@Aspect與Interceptor的都是基於spring aop的實現,@Aspect粒度更細

攔截順序:filter—>Interceptor—->@Aspect

Filter,攔截器,aop攔截的實現與區別

Filter,攔截器,aop攔截的實現與區別

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

orb_slam整體編程思路及代碼解析
c井動態調用WebService

TAG:程序員小新人學習 |