共计 1911 个字符,预计需要花费 5 分钟才能阅读完成。
1. 自定义过滤器实现接口 HandlerInterceptor
package com.huacheng.config;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TimeInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println(">>>>>>>>>>>preHandle 执行了 <<<<<<<<<<<<<<<<<<");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {System.out.println(">>>>>>>>>>>postHandle 执行了 <<<<<<<<<<<<<<<<<<");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {System.out.println(">>>>>>>>>>>afterCompletion 执行了 <<<<<<<<<<<<<<<<<<");
}
}
2. 定义一个配置类,把这个自定义的过滤器注册进去
package com.huacheng.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private TimeInterceptor timeInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(timeInterceptor);
}
}
3. 写一个控制器测试
package com.huacheng.controller;
import com.huacheng.domain.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {@PostMapping("/user/getUser")
public String getUser(User user) {System.out.println(user);
return "hello";
}
}
4. 应用 postman 工具测试
控制台打印如下
postman 工具相应后果
正文完
发表至: springboot
2020-07-20