1、编写拦截器实现类,此类必须实现接口 HandlerInterceptor,然后重写里面需要的三个比较常用的方法,实现自己的业务逻辑代码
如:OneInterceptor
1 package com.leecx.interceptors.interceptor;
2
3
4 import com.leecx.pojo.LeeJSONResult;
5 import com.leecx.utils.JsonUtils;
6 import org.springframework.web.servlet.HandlerInterceptor;
7 import org.springframework.web.servlet.ModelAndView;
8
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.UnsupportedEncodingException;
14
15 public class OneInterceptor implements HandlerInterceptor{
16
17 /**
18 * 在请求处理之前进行调用(Controller方法调用之前)
19 */
20 @Override
21 public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
22
23 System.out.println("=====================");
24 if (true) {
25 returnErrorResponse(httpServletResponse, LeeJSONResult.errorMsg("被one拦截..."));
26 }
27
28 System.out.println("被one拦截...");
29
30 return false;
31 }
32
33 /**
34 * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
35 */
36 @Override
37 public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
38
39 }
40
41 /**
42 * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
43 */
44 @Override
45 public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
46
47 }
48
49 public void returnErrorResponse(HttpServletResponse response, LeeJSONResult result) throws IOException, UnsupportedEncodingException {
50 OutputStream out = null;
51 try{
52 response.setCharacterEncoding("utf-8");
53 response.setContentType("text/json");
54 out = response.getOutputStream();
55 out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
56 out.flush();
57 } finally{
58 if(out!=null){
59 out.close();
60 }
61 }
62 }
63 }
说明:
1、preHandle 方法会在请求处理之前进行调用(Controller方法调用之前)
2、postHandle 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
3、afterCompletion 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
2、编写拦截器配置文件主类 WebMvcConfigurer 此类必须继承 WebMvcConfigurerAdapter 类,并重写其中的方法 addInterceptors 并且在主类上加上注解 @Configuration
如:WebMvcConfigurer
1 package com.leecx.interceptors.config;
2
3 import com.leecx.interceptors.interceptor.OneInterceptor;
4 import com.leecx.interceptors.interceptor.TwoInterceptor;
5 import org.springframework.context.annotation.Configuration;
6 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
8
9 @Configuration
10 public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
11
12 /**
13 * <p>Title:</p>
14 * <p>Description:重写增加自定义拦截器的注册,某一个拦截器需要先注册进来,才能工作</p>
15 * param[1]: null
16 * return:
17 * exception:
18 * date:2018/4/18 0018 下午 17:29
19 * author:段美林[duanml@neusoft.com]
20 */
21 @Override
22 public void addInterceptors(InterceptorRegistry registry) {
23
24 registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
25
26 registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/one/**")
27 .addPathPatterns("/two/**");
28
29 super.addInterceptors(registry);
30 }
31 }
说明:
拦截器的执行是会根据 registry 注入的先后顺序执行,比如:/one/** 同时被 OneInterceptor、TwoInterceptor 拦截,但会先执行 OneInterceptor拦截的业务请求,因为它先注入进来的。
3、在controller业务层,只要请求的地址为 拦截器 申明的需要拦截地址即可进入相应的业务处理。
如:OneInterceptorController 这个controller 类的所有实现方法都会被 拦截器 OneInterceptor 所拦截到。
复制代码
1 package com.leecx.controller;
2
3 import java.util.ArrayList;
4 import java.util.Date;
5 import java.util.List;
6
7 import org.springframework.stereotype.Controller;
8 import org.springframework.ui.ModelMap;
9 import org.springframework.web.bind.annotation.PostMapping;
10 import org.springframework.web.bind.annotation.RequestMapping;
11
12 import com.leecx.pojo.User;
13
14 @Controller
15 @RequestMapping("/one")
16 public class OneInterceptorController {
17
18 @RequestMapping("/index")
19 public String index(ModelMap map) {
20 System.out.println("=========one is index");
21 map.addAttribute("name", "itzixi22");
22 return "thymeleaf/index";
23 }
24
25 @RequestMapping("center")
26 public String center() {
27 return "thymeleaf/center/center";
28 }
29
30 @RequestMapping("test")
31 public String test(ModelMap map) {
32
33 User user = new User();
34 user.setAge(18);
35 user.setName("manager");
36 user.setPassword("123456");
37 user.setBirthday(new Date());
38
39 map.addAttribute("user", user);
40
41
42 User u1 = new User();
43 u1.setAge(19);
44 u1.setName("itzixi");
45 u1.setPassword("123456");
46 u1.setBirthday(new Date());
47
48 User u2 = new User();
49 u2.setAge(17);
50 u2.setName("LeeCX");
51 u2.setPassword("123456");
52 u2.setBirthday(new Date());
53
54 List<User> userList = new ArrayList<>();
55 userList.add(user);
56 userList.add(u1);
57 userList.add(u2);
58
59 map.addAttribute("userList", userList);
60
61 return "thymeleaf/test";
62 }
63
64 @PostMapping("postform")
65 public String postform(User user) {
66 System.out.println(user.getName());
67 return "redirect:/th/test";
68 }
69 }