Java Code Examples for org.springframework.web.method.HandlerMethod#getBean()

The following examples show how to use org.springframework.web.method.HandlerMethod#getBean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserInterceptorHandler.java    From youkefu with Apache License 2.0 6 votes vote down vote up
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
	boolean filter = false; 
    User user = (User) request.getSession(true).getAttribute(UKDataContext.USER_SESSION_NAME) ;
    if(handler instanceof HandlerMethod) {
     HandlerMethod  handlerMethod = (HandlerMethod ) handler ;
     Menu menu = handlerMethod.getMethod().getAnnotation(Menu.class) ;
     if(user != null || (menu!=null && menu.access()) || handlerMethod.getBean() instanceof BasicErrorController){
     	filter = true;
     }
     
     if(!filter){
     	response.sendRedirect("/login.html");
     }
    }else {
    	filter =true ;
    }
    return filter ; 
}
 
Example 2
Source File: BootWebUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static <T> T currentController(){
	HandlerMethod handler = currentHandlerMethod();
	if(handler!=null){
		return (T)handler.getBean();
	}
	return null;
}
 
Example 3
Source File: AbstractHandlerMethodMapping.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void assertUniqueMethodMapping(HandlerMethod newHandlerMethod, T mapping) {
	HandlerMethod handlerMethod = this.mappingLookup.get(mapping);
	if (handlerMethod != null && !handlerMethod.equals(newHandlerMethod)) {
		throw new IllegalStateException(
				"Ambiguous mapping. Cannot map '" +	newHandlerMethod.getBean() + "' method \n" +
				newHandlerMethod + "\nto " + mapping + ": There is already '" +
				handlerMethod.getBean() + "' bean method\n" + handlerMethod + " mapped.");
	}
}
 
Example 4
Source File: AbstractHandlerMethodExceptionResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the handler is a {@link HandlerMethod} and then delegates to the
 * base class implementation of {@link #shouldApplyTo(HttpServletRequest, Object)}
 * passing the bean of the {@code HandlerMethod}. Otherwise returns {@code false}.
 */
@Override
protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
	if (handler == null) {
		return super.shouldApplyTo(request, handler);
	}
	else if (handler instanceof HandlerMethod) {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		handler = handlerMethod.getBean();
		return super.shouldApplyTo(request, handler);
	}
	else {
		return false;
	}
}
 
Example 5
Source File: BootWebUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static <T> T currentTypeController(Class<T> clazz){
	HandlerMethod handler = currentHandlerMethod();
	if(handler!=null && clazz.isInstance(handler.getBean())){
		return (T)handler.getBean();
	}
	return null;
}
 
Example 6
Source File: AbstractHandlerMethodExceptionResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if the handler is a {@link HandlerMethod} and then delegates to the
 * base class implementation of {@code #shouldApplyTo(HttpServletRequest, Object)}
 * passing the bean of the {@code HandlerMethod}. Otherwise returns {@code false}.
 */
@Override
protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
	if (handler == null) {
		return super.shouldApplyTo(request, handler);
	}
	else if (handler instanceof HandlerMethod) {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		handler = handlerMethod.getBean();
		return super.shouldApplyTo(request, handler);
	}
	else {
		return false;
	}
}
 
Example 7
Source File: DefaultRenderInterceptor.java    From Aooms with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, Object handler ,ModelAndView modelAndView){
    if(!isRender(request)){
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Object controllerBean = handlerMethod.getBean();
            if(controllerBean instanceof AoomsAbstractController){
                AoomsAbstractController controller = (AoomsAbstractController) controllerBean;
                controller.renderJson();
            }
        }
    }
}
 
Example 8
Source File: AbstractHandlerMethodMapping.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void assertUniqueMethodMapping(HandlerMethod newHandlerMethod, T mapping) {
	HandlerMethod handlerMethod = this.mappingLookup.get(mapping);
	if (handlerMethod != null && !handlerMethod.equals(newHandlerMethod)) {
		throw new IllegalStateException(
				"Ambiguous mapping. Cannot map '" +	newHandlerMethod.getBean() + "' method \n" +
				newHandlerMethod + "\nto " + mapping + ": There is already '" +
				handlerMethod.getBean() + "' bean method\n" + handlerMethod + " mapped.");
	}
}
 
Example 9
Source File: AbstractHandlerMethodExceptionResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Checks if the handler is a {@link HandlerMethod} and then delegates to the
 * base class implementation of {@code #shouldApplyTo(HttpServletRequest, Object)}
 * passing the bean of the {@code HandlerMethod}. Otherwise returns {@code false}.
 */
@Override
protected boolean shouldApplyTo(HttpServletRequest request, @Nullable Object handler) {
	if (handler == null) {
		return super.shouldApplyTo(request, null);
	}
	else if (handler instanceof HandlerMethod) {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		handler = handlerMethod.getBean();
		return super.shouldApplyTo(request, handler);
	}
	else {
		return false;
	}
}
 
Example 10
Source File: ControllerMethodResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Find an {@code @ExceptionHandler} method in {@code @ControllerAdvice}
 * components or in the controller of the given {@code @RequestMapping} method.
 */
@Nullable
public InvocableHandlerMethod getExceptionHandlerMethod(Throwable ex, HandlerMethod handlerMethod) {
	Class<?> handlerType = handlerMethod.getBeanType();

	// Controller-local first...
	Object targetBean = handlerMethod.getBean();
	Method targetMethod = this.exceptionHandlerCache
			.computeIfAbsent(handlerType, ExceptionHandlerMethodResolver::new)
			.resolveMethodByThrowable(ex);

	if (targetMethod == null) {
		// Global exception handlers...
		for (ControllerAdviceBean advice : this.exceptionHandlerAdviceCache.keySet()) {
			if (advice.isApplicableToBeanType(handlerType)) {
				targetBean = advice.resolveBean();
				targetMethod = this.exceptionHandlerAdviceCache.get(advice).resolveMethodByThrowable(ex);
				if (targetMethod != null) {
					break;
				}
			}
		}
	}

	if (targetMethod == null) {
		return null;
	}

	InvocableHandlerMethod invocable = new InvocableHandlerMethod(targetBean, targetMethod);
	invocable.setArgumentResolvers(this.exceptionHandlerResolvers);
	return invocable;
}
 
Example 11
Source File: ControllerMethodResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Find an {@code @ExceptionHandler} method in {@code @ControllerAdvice}
 * components or in the controller of the given {@code @RequestMapping} method.
 */
@Nullable
public InvocableHandlerMethod getExceptionHandlerMethod(Throwable ex, HandlerMethod handlerMethod) {

	Class<?> handlerType = handlerMethod.getBeanType();

	// Controller-local first...
	Object targetBean = handlerMethod.getBean();
	Method targetMethod = this.exceptionHandlerCache
			.computeIfAbsent(handlerType, ExceptionHandlerMethodResolver::new)
			.resolveMethodByThrowable(ex);

	if (targetMethod == null) {
		// Global exception handlers...
		for (ControllerAdviceBean advice : this.exceptionHandlerAdviceCache.keySet()) {
			if (advice.isApplicableToBeanType(handlerType)) {
				targetBean = advice.resolveBean();
				targetMethod = this.exceptionHandlerAdviceCache.get(advice).resolveMethodByThrowable(ex);
				if (targetMethod != null) {
					break;
				}
			}
		}
	}

	if (targetMethod == null) {
		return null;
	}

	InvocableHandlerMethod invocable = new InvocableHandlerMethod(targetBean, targetMethod);
	invocable.setArgumentResolvers(this.exceptionHandlerResolvers);
	return invocable;
}
 
Example 12
Source File: TokenIntercepter.java    From gpmall with Apache License 2.0 5 votes vote down vote up
private boolean isAnoymous(HandlerMethod handlerMethod){
    Object bean=handlerMethod.getBean();
    Class clazz=bean.getClass();
    if(clazz.getAnnotation(Anoymous.class)!=null){
        return true;
    }
    Method method=handlerMethod.getMethod();
    return method.getAnnotation(Anoymous.class)!=null;
}
 
Example 13
Source File: LogIntercreptorHandler.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
		Object arg2) throws Exception {
	HandlerMethod  handlerMethod = (HandlerMethod ) arg2 ;
    Object hander = handlerMethod.getBean() ;
    if(hander instanceof Handler) {
    	((Handler)hander).setStarttime(System.currentTimeMillis());
    }
	return true;
}
 
Example 14
Source File: AbstractHandlerMethodMapping.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void validateMethodMapping(HandlerMethod handlerMethod, T mapping) {
	// Assert that the supplied mapping is unique.
	HandlerMethod existingHandlerMethod = this.mappingLookup.get(mapping);
	if (existingHandlerMethod != null && !existingHandlerMethod.equals(handlerMethod)) {
		throw new IllegalStateException(
				"Ambiguous mapping. Cannot map '" + handlerMethod.getBean() + "' method \n" +
				handlerMethod + "\nto " + mapping + ": There is already '" +
				existingHandlerMethod.getBean() + "' bean method\n" + existingHandlerMethod + " mapped.");
	}
}
 
Example 15
Source File: AbstractHandlerMethodExceptionResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Checks if the handler is a {@link HandlerMethod} and then delegates to the
 * base class implementation of {@code #shouldApplyTo(HttpServletRequest, Object)}
 * passing the bean of the {@code HandlerMethod}. Otherwise returns {@code false}.
 */
@Override
protected boolean shouldApplyTo(HttpServletRequest request, @Nullable Object handler) {
	if (handler == null) {
		return super.shouldApplyTo(request, null);
	}
	else if (handler instanceof HandlerMethod) {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		handler = handlerMethod.getBean();
		return super.shouldApplyTo(request, handler);
	}
	else {
		return false;
	}
}
 
Example 16
Source File: AbstractHandlerMethodMapping.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void validateMethodMapping(HandlerMethod handlerMethod, T mapping) {
	// Assert that the supplied mapping is unique.
	HandlerMethod existingHandlerMethod = this.mappingLookup.get(mapping);
	if (existingHandlerMethod != null && !existingHandlerMethod.equals(handlerMethod)) {
		throw new IllegalStateException(
				"Ambiguous mapping. Cannot map '" + handlerMethod.getBean() + "' method \n" +
				handlerMethod + "\nto " + mapping + ": There is already '" +
				existingHandlerMethod.getBean() + "' bean method\n" + existingHandlerMethod + " mapped.");
	}
}
 
Example 17
Source File: LoginInterceptor.java    From star-zone with Apache License 2.0 4 votes vote down vote up
@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            logger.info("进入拦截器...........");
            Object controller = handlerMethod.getBean();
            printParameters(request, controller);
            // 访问需要登录的接口那些
            // 被@AuthController注解的Controller
            boolean isPresent = controller.getClass().isAnnotationPresent(AuthController.class);

            if (!isPresent) { // 不是需要登录验证的Controller,放行
                return true;
            } else {
                String userIdStr = request.getHeader("userId");
                String token = request.getHeader("token");
                if (!StringUtils.isEmpty(userIdStr)) {
                    long userId = Long.valueOf(userIdStr);
                    if (userId > 0) {
//                        logger.info("访问需要登录的接口(Authed)...........");
                        if (StringUtils.isEmpty(token)) {
                            flushError(response, AuthResponseCode.TOKEN_IS_NULL, AuthResponseCode.TOKEN_IS_NULL_DESC);
                            return false;
                        }
                        Passport passport = loginIntercepterService.getPassport(userId);
                        String storedToken = passport.getToken();
                        if (StringUtils.isEmpty(storedToken)) {
                            flushError(response, AuthResponseCode.TOKEN_EXPIRED, AuthResponseCode.TOKEN_EXPIRED_DESC);
                            return false;
                        } else if (!storedToken.equals(token)) {
                            flushError(response, AuthResponseCode.TOKEN_INVALID, AuthResponseCode.TOKEN_INVALID_DESC);
                            return false;
                        }

                    } // 被@AuthController注解的 结束
                } else {
                    flushError(response, AuthResponseCode.USER_ID_IS_NULL, AuthResponseCode.USER_ID_IS_NULL_DESC);
                    return false;
                }

            }


        }     //HandlerMethod 结束

        boolean flag = isPermission(request, response);
//        logger.info("isPermission:" + flag);
        return flag;
    }
 
Example 18
Source File: BaseAuthInterceptor.java    From Ffast-Java with MIT License 4 votes vote down vote up
/**
 * 拦截登录&权限
 *
 * @param request
 * @param response
 * @param handler
 * @return
 * @throws Exception
 */
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) throws Exception {
    logger.debug("###############进入拦截器###############");
    String path = (request.getRequestURI().replace(request.getContextPath(), ""));
    StringBuilder permissionName = new StringBuilder();
    boolean loginVerify = false;

    HandlerMethod hMethod = null;
    String beanName = null;
    if (handler instanceof HandlerMethod) {
        hMethod = ((HandlerMethod) handler);
        Object bean = hMethod.getBean();
        Logined loginedClassAnnotation = bean.getClass().getAnnotation(Logined.class);
        Logined loginedMethodAnnotation = hMethod.getMethodAnnotation(Logined.class);
        if (loginedClassAnnotation != null) {
            if (loginedClassAnnotation.notEffectSelf() &&
                    hMethod.getMethod().getDeclaringClass().getName().equals(bean.getClass().getName())) {
                loginVerify = false;
            } else {
                loginVerify = true;
            }
        }
        if (loginedMethodAnnotation != null) {
            if (loginedMethodAnnotation.notEffectSelf()) {
                loginVerify = false;
            } else {
                loginVerify = true;
            }
        }
        Permission classPermission = bean.getClass().getAnnotation(Permission.class);
        Permission methodPermission = hMethod.getMethodAnnotation(Permission.class);


        if (methodPermission != null) {
            //如果是独立的权限验证
            if (methodPermission.alone()) {
                permissionName = new StringBuilder(methodPermission.value());
            } else {
                // 如果方法权限不为空才会和类权限组合
                if (classPermission != null && StringUtils.isNotEmpty(methodPermission.value())) {
                    permissionName.append(classPermission.value());
                    permissionName.append(":");
                    permissionName.append(methodPermission.value());
                }
            }
        }
        beanName = bean.getClass().getName();
    }

    if (loginVerify) {
        Class<T> tClass = ReflectionKit.getSuperClassGenricType(this.getClass(), 0);
        T loginUser = operatorUtils.getTokenUser(request, tClass);
        request.setAttribute("loginUser", loginUser);
        if (loginUser == null) {
            //未登录
            notLogin(response);
            logger.error(beanName + " path:" + path + " [未登录]");
            return false;
        } else if (StringUtils.isNotEmpty(permissionName) &&
                !verifyPerms(loginUser.getHasRoleId(), permissionName.toString())) {
            //没有权限
            notPermission(response);
            logger.error(beanName + " loginId:" + loginUser.getUserId() +
                    " loginName:" + loginUser.getUserName() + " funcId:" + permissionName + " [没有权限]");
            return false;
        }
    }

    return true;

}
 
Example 19
Source File: LoginInterceptor.java    From star-zone with Apache License 2.0 4 votes vote down vote up
@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            logger.info("进入拦截器...........");
            Object controller = handlerMethod.getBean();
            printParameters(request, controller);
            // 访问需要登录的接口那些
            // 被@AuthController注解的Controller
            boolean isPresent = controller.getClass().isAnnotationPresent(AuthController.class);

            if (!isPresent) { // 不是需要登录验证的Controller,放行
                return true;
            } else {
                String userIdStr = request.getHeader("userId");
                String token = request.getHeader("token");
                if (!StringUtils.isEmpty(userIdStr)) {
                    long userId = Long.valueOf(userIdStr);
                    if (userId > 0) {
//                        logger.info("访问需要登录的接口(Authed)...........");
                        if (StringUtils.isEmpty(token)) {
                            flushError(response, AuthResponseCode.TOKEN_IS_NULL, AuthResponseCode.TOKEN_IS_NULL_DESC);
                            return false;
                        }
                        Passport passport = loginIntercepterService.getPassport(userId);
                        String storedToken = passport.getToken();
                        if (StringUtils.isEmpty(storedToken)) {
                            flushError(response, AuthResponseCode.TOKEN_EXPIRED, AuthResponseCode.TOKEN_EXPIRED_DESC);
                            return false;
                        } else if (!storedToken.equals(token)) {
                            flushError(response, AuthResponseCode.TOKEN_INVALID, AuthResponseCode.TOKEN_INVALID_DESC);
                            return false;
                        }

                    } // 被@AuthController注解的 结束
                } else {
                    flushError(response, AuthResponseCode.USER_ID_IS_NULL, AuthResponseCode.USER_ID_IS_NULL_DESC);
                    return false;
                }

            }


        }     //HandlerMethod 结束

        boolean flag = isPermission(request, response);
//        logger.info("isPermission:" + flag);
        return flag;
    }
 
Example 20
Source File: LogIntercreptorHandler.java    From youkefu with Apache License 2.0 4 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
		Object arg2, ModelAndView arg3) throws Exception {
	HandlerMethod  handlerMethod = (HandlerMethod ) arg2 ;
    Object hander = handlerMethod.getBean() ;
    RequestMapping obj = handlerMethod.getMethod().getAnnotation(RequestMapping.class) ;
    if(!StringUtils.isBlank(request.getRequestURI()) && !(request.getRequestURI().startsWith("/message/ping") || request.getRequestURI().startsWith("/res/css") || request.getRequestURI().startsWith("/error")  || request.getRequestURI().startsWith("/im/"))){
    	RequestLog log = new RequestLog();
	    log.setEndtime(new Date()) ;
	    
		if(obj!=null) {
			log.setName(obj.name());
		}
		log.setMethodname(handlerMethod.toString()) ;
		log.setIp(request.getRemoteAddr()) ;
		if(hander!=null) {
			log.setClassname(hander.getClass().toString()) ;
			if(hander instanceof Handler && ((Handler)hander).getStarttime() != 0) {
		    	log.setQuerytime(System.currentTimeMillis() - ((Handler)hander).getStarttime());
		    }
		}
		log.setUrl(request.getRequestURI());
		
		log.setHostname(request.getRemoteHost()) ;
		log.setEndtime(new Date());
		log.setType(UKDataContext.LogTypeEnum.REQUEST.toString()) ;
		User user = (User) request.getSession(true).getAttribute(UKDataContext.USER_SESSION_NAME) ;
		if(user!=null){
			log.setUserid(user.getId()) ;
			log.setUsername(user.getUsername()) ;
			log.setUsermail(user.getEmail()) ;
			log.setOrgi(user.getOrgi());
		}
		StringBuffer str = new StringBuffer();
		Enumeration<String> names = request.getParameterNames();
		while(names.hasMoreElements()){
			String paraName=(String)names.nextElement();
			if(paraName.indexOf("password") >= 0) {
				str.append(paraName).append("=").append(UKTools.encryption(request.getParameter(paraName))).append(",");
			}else {
				str.append(paraName).append("=").append(request.getParameter(paraName)).append(",");
			}
		}
		
		Menu menu = handlerMethod.getMethod().getAnnotation(Menu.class) ;
		if(menu!=null){
			log.setFuntype(menu.type());
			log.setFundesc(menu.subtype());
			log.setName(menu.name());
		}
		
		log.setParameters(str.toString());
		UKTools.published(log);
    }
}