import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MapKV{
String keyName() default "key";
String valueName() default "value";
}
作用于方法
@RestController
@RequestMapping("/ws")
public class DemoController {
@Resource
private WebSocket webSocket;
@MapKV(keyName = "12",valueName = "123")
@GetMapping("/demos")
public void demo() {
webSocket.sendOneMessage(String.valueOf(123),"你好");
}
}
创建自定义过滤器 继承HandlerInterceptor
重写所需方法
- preHandle :Controller方法处理之前
- postHandle:preHandle处理结束 返回true 并且Controller处理结束 DispatcherServlet进行视图的渲染之前 多用于操作返回内容
- afterCompletion:视图渲染之后 多用于清理资源
public class MapKVInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod method =(HandlerMethod) handler;
MapKV methodAnnotation = method.getMethodAnnotation(MapKV.class);
if(methodAnnotation != null) {
log.info(methodAnnotation.keyName());
log.info(methodAnnotation.valueName());
log.info("MapKV method annotation");
}
return true;
}
}
配置过滤器
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MapKVInterceptor()).addPathPatterns("/**");
}
}
参考:Spring注解@EnableWebMvc使用坑点解析



