在业务有时候会遇到需要定时下线某些功能,在指定时间之后某些功能不可用,前端屏蔽之后是当然不够的,还需要后端屏蔽相关的业务逻辑。
本文是通过注解方式提供对SpringMVC中Controller层的拦截,使其到指定时间方法不可用,达到定时屏蔽的功能。
同时,向前端传输是否隐藏这个属性,如果是jsp页面的话可以通过request.getAttribute(“isHidden”)来获取值,从而判断是否应该隐藏。
这个地方有个坑,前端获取到boolean值的时候需要通过Boolean.parseBoolean(String a)去转换,否则直接获取的是Object类型的数据。
public class OfflineInterceptor extends HandlerInterceptorAdapter{
private static Logger LOGGER = LoggerFactory.getLogger(OfflineInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
LOGGER.info("-------Check Offline Annotation begin -------");
if(handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod)handler;
//获取方法上的注解
OfflineAnnotation offlineAnnotation = handlerMethod.getMethodAnnotation(OfflineAnnotation.class);
if (offlineAnnotation == null) {
LOGGER.info("-------Check Offline Annotation end ------- OfflineAnnotation is not set.");
return true;
}
String date = offlineAnnotation.date();
if (date == null || date.isEmpty()) {
LOGGER.info("-------Check Offline Annotation end ------- Offline Date is not set, offline immediately.");
response.sendRedirect("/errors/error");
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date offlineDate = sdf.parse(date);
Date nowDate = new Date();
boolean isOffonline = nowDate.after(offlineDate);
boolean isHidden = false;
if (nowDate.after(offlineDate)){
isHidden = true;
}
request.setAttribute("isHidden", isHidden);
LOGGER.info("-------Check Offline Annotation end ------- The offline mark is "+isOffonline);
if (isOffonline) {
response.sendRedirect(request.getContextPath()+"/errors/error");
return false;
}
}
LOGGER.info("-------Check Offline Annotation end -------");
return true;
}
}
这下面是注解的相关配置
@Target指定该注解应用于方法上
@Retention则指定该注解运行时生效
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 OfflineAnnotation {
String date() default "";
}