问题描述
@Service
@GetMapping
public Foo findByFooId(@RequestParam(name = "fid") String fooId) {
return fooService.findByFooId(fooId);
}
我想在 FooService 中使用不同的方法触发并保存查看过 Foo 的人。 它就像一个用于成功响应 findByFooId 的 postconstruct 回调。怎样才能做到这一点
解决方法
一种方法是自定义 HandlerInterceptor
实现。
- 拦截器的定义
public class FooViewerInterceptor extends HandlerInterceptorAdapter {
@Autowired
FooService fooService;
@Override
public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView)
throws Exception {
// if response succeeded ? http response code = 200 ?
// extract the "who" logic
// extract the fooId from request path
fooService.viewedBy(fooId,userId); // example...
}
}
- 注册拦截器。请注意使用自定义拦截器实例指定的路径模式.. 只是一个示例。
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooViewerInterceptor()).addPathPatterns("/foo/**");
}
}