美文网首页
2019-08-24 注解和AOP在项目中的使用

2019-08-24 注解和AOP在项目中的使用

作者: tanbin_tech | 来源:发表于2019-08-24 11:02 被阅读0次

需求:在请求从controller出来之后,判断请求头是否包含特定字符,如果包含,就往modelMap中写入标志,这样在返回视图的时候,根据标志决定返回整个页面还是碎片页面,通过这样来实现单页面应用(SAP)。

实现步骤

  1. 定义注解(注解本身并不做什么事,只是触发AOP的媒介):
@Target(ElementType.METHOD)   //用在方法上
@Retention(RetentionPolicy.RUNTIME)  //保留至运行时
@Documented //生成文档时也记录进去
public @interface Page {

}
  1. 定义aspect(包含切点)
public class PageAspect {

    @After("@annotation(Page)")
    public void afterHttp(JoinPoint joinPoint) {
       // 获取 request 参数
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
        String httpType = request.getHeader("http-type");
        boolean f = !"ajax".equals(httpType);
        modelMap.put("loadAll", f);
    }
}

简单两步,就可以在使用@Page注解的地方进行请求头判断,减少代码量。

相关文章

网友评论

      本文标题:2019-08-24 注解和AOP在项目中的使用

      本文链接:https://www.haomeiwen.com/subject/gcmfectx.html