定时下线小工具

在业务有时候会遇到需要定时下线某些功能,在指定时间之后某些功能不可用,前端屏蔽之后是当然不够的,还需要后端屏蔽相关的业务逻辑。

本文是通过注解方式提供对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 "";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值