java拦截器实例

本文通过实例介绍了如何使用Java拦截器配合自定义注解,实现对用户登录状态的检查,以及控制特定游戏活动的时间限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class EntranceInterceptor extends HandlerInterceptorAdapter {
	
	private Logger LOG = Logger.getLogger(EntranceInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		MDC.put(LogUtil.KEY_REQUEST_ID, RandomStringUtils.randomAlphanumeric(8));
		LOG.debug(LogUtil.getLogStr(request));
		
		//过滤掉静态资源
		if(handler instanceof HandlerMethod){
			
			//获取游戏
			String url = request.getRequestURI();
			if(!"".equals(url) && !"/".equals(url)){
				String str = url.substring(url.indexOf("/") + 1);
				StringTokenizer st = new StringTokenizer(str, "/");
				
				String game = "";
				int c = 0;
				while (st.hasMoreTokens()) {
					if(++c == 2){
						game = st.nextToken();
					}
					st.nextToken();
				}
				LOG.debug(LogUtil.getLogStr("[当前访问活动名称]:[" + game + "]"));
				TempleConfigContext.setCurrentGameActivity(GameActivityEnum.getGameActivityEnum(game));
			}
			
			//是否有AjaxAnno注解
			HandlerMethod method = (HandlerMethod) handler;
			AjaxAnno anno = method.getBean().getClass().getAnnotation(AjaxAnno.class);
			if (anno != null || (anno = method.getMethod().getAnnotation(AjaxAnno.class)) != null) {
				TempleConfigContext.setCurrentRequestType(TempleConfigContext.AJAX_REQUEST_TYPE);
			}
			
			LoginRequired required = method.getBean().getClass().getAnnotation(LoginRequired.class);
			if (required != null || (required = method.getMethod().getAnnotation(LoginRequired.class)) != null) {
				//验证是否登录
				GameActivityEnum activity = TempleConfigContext.getCurrentGameActivity();
				if (request.getSession().getAttribute(activity.getActivity() + "_" + Constant.MANAGER_SESSION_LOGIN_USER) == null) {// 判断session里是否有用户信息
					throw new BusinessException(CommonStateEnum.BADREQ_PARA_SESSION_TIMEOUT, "您还没有登录或者您的登录已经过期");
				}
			}
			
			PassAction pass = method.getBean().getClass().getAnnotation(PassAction.class);
			if (pass == null && (pass = method.getMethod().getAnnotation(PassAction.class)) == null) {
				//验证是否过期
				Date[] limit = Constant.getHdLimitTime(TempleConfigContext.getCurrentGameActivity().getActivity()); 
				if(null != limit){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date date = new Date();
					if(null != limit[0] && date.before(limit[0])){
						CommonStateEnum error = CommonStateEnum.BADREQ_API_HD_NOT_SATRT;
						throw new BusinessException(error, error.getMessage(sdf.format(limit[0])));
					}
					
					if(null != limit[1] && date.after(limit[1])){
						CommonStateEnum error = CommonStateEnum.BADREQ_API_HD_ALREADY_END;
						throw new BusinessException(error, error.getMessage(sdf.format(limit[0]), sdf.format(limit[1])));
					}
				}
			}			
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		MDC.remove(LogUtil.KEY_REQUEST_ID);
	}
}

java拦截器 配合 自定义注解实现控制用户是否登录   控制游戏活动时间

@Retention(value = RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface PassAction {
}
PassAction为空 则表示 不用验证时间,不为空则需要验证游戏活动时间


@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface LoginRequired {
	
}
LoginRequired用户验证是否登陆 有些controller需要登录才能继续下面逻辑代码,如果判断登录的逻辑在每个controller里都写一遍代码冗余很多 所以基于aop的思想通过注解加拦截器的方式来精简代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值