每一次访问文章,文章的浏览量就加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后再获取对应的值;