使用拦截器做文章访问量功能(注解)

每一次访问文章,文章的浏览量就加1,如果该cookie已经访问过,则不增加访问量

拦截器拦截方法
首先设置好拦截器

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface VisitRequired {

}
public class VisitInterceptor extends HandlerInterceptorAdapter{
    @Autowired
    private ArticleVisitService articleVisitService;

    @Autowired
    private ArticleService articleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;
            VisitRequired annotation=getClassOrMethodAnnotationByClassFirst(method);
            if (null != annotation){
                String guest_sid = getCookieValue(request,"guest_sid");
                Map map= (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                Integer articleId = Integer.parseInt((String) map.get("id")) ;
                ArticleVisit articleVisit = articleVisitService.findArticleVisitByguest_sid(guest_sid);
                if (articleVisit == null){
                    Article article = articleService.findArticleByid(articleId);
                    article.setVisitCount(article.getVisitCount()+1);
                    articleService.update(article);
                    articleVisitService.setCookies(response,articleId); //设置cookie
                }
            }
        }
         return super.preHandle(request, response, handler);
    }

    private VisitRequired getClassOrMethodAnnotationByClassFirst(HandlerMethod method) {
        VisitRequired annotation = method.getBeanType().getAnnotation(VisitRequired.class);
        if (null == annotation) {
            annotation = method.getMethodAnnotation(VisitRequired.class);
        }
        return annotation;
    }

    public static String getCookieValue(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    return cookie.getValue();
                }
            }
        }
        return "";
    }
}

然后将配置好拦截器…
将拦截器添加到方法上

    @VisitRequired
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Result getArticleDetails(@PathVariable Integer id){
        //这里返回文章内容
    }

ps:关于拦截器怎么获取到@PathVariable 的值
可用
Map map= (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
得到Map后再获取对应的值;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值