org.springframework.web.method.HandlerMethod源码实例Demo

org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.web.method.HandlerMethod源码实例Demo

下面列出了org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.web.method.HandlerMethod 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private void testHttpOptions(String requestURI, Set<HttpMethod> allowedMethods) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options(requestURI));
	HandlerMethod handlerMethod = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();

	BindingContext bindingContext = new BindingContext();
	InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
	Mono<HandlerResult> mono = invocable.invoke(exchange, bindingContext);

	HandlerResult result = mono.block();
	assertNotNull(result);

	Object value = result.getReturnValue();
	assertNotNull(value);
	assertEquals(HttpHeaders.class, value.getClass());
	assertEquals(allowedMethods, ((HttpHeaders) value).getAllow());
}
 
源代码2 项目: spring-cloud-sleuth   文件: TraceWebFilter.java
private void addClassNameTag(Object handler, Span span) {
	if (handler == null) {
		return;
	}
	String className;
	if (handler instanceof HandlerMethod) {
		className = ((HandlerMethod) handler).getBeanType().getSimpleName();
	}
	else {
		className = handler.getClass().getSimpleName();
	}
	if (log.isDebugEnabled()) {
		log.debug("Adding a class tag with value [" + className
				+ "] to a span " + span);
	}
	span.tag(MVC_CONTROLLER_CLASS_KEY, className);
}
 
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
	HandlerMethod handlerMethod = createHandlerMethod(handler, method);
	Class<?> beanType = handlerMethod.getBeanType();
	CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
	CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);

	if (typeAnnotation == null && methodAnnotation == null) {
		return null;
	}

	CorsConfiguration config = new CorsConfiguration();
	updateCorsConfig(config, typeAnnotation);
	updateCorsConfig(config, methodAnnotation);

	if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
		for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
			config.addAllowedMethod(allowedMethod.name());
		}
	}
	return config.applyPermitDefaultValues();
}
 
源代码4 项目: springdoc-openapi   文件: OpenApiResource.java
/**
 * Calculate path.
 *
 * @param restControllers the rest controllers
 * @param map the map
 */
protected void calculatePath(Map<String, Object> restControllers, Map<RequestMappingInfo, HandlerMethod> map) {
	for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
		RequestMappingInfo requestMappingInfo = entry.getKey();
		HandlerMethod handlerMethod = entry.getValue();
		PatternsRequestCondition patternsRequestCondition = requestMappingInfo.getPatternsCondition();
		Set<String> patterns = patternsRequestCondition.getPatterns();
		Map<String, String> regexMap = new LinkedHashMap<>();
		for (String pattern : patterns) {
			String operationPath = PathUtils.parsePath(pattern, regexMap);
			if (((actuatorProvider.isPresent() && actuatorProvider.get().isRestController(operationPath))
					|| isRestController(restControllers, handlerMethod, operationPath))
					&& isPackageToScan(handlerMethod.getBeanType().getPackage())
					&& isPathToMatch(operationPath)) {
				Set<RequestMethod> requestMethods = requestMappingInfo.getMethodsCondition().getMethods();
				// default allowed requestmethods
				if (requestMethods.isEmpty())
					requestMethods = this.getDefaultAllowedHttpMethods();
				calculatePath(handlerMethod, operationPath, requestMethods);
			}
		}
	}
}
 
@Test
public void failOnUndocumentedParams() throws Exception {
    HandlerMethod handlerMethod = createHandlerMethod("addItem", Integer.class, String.class,
            int.class, String.class, Optional.class);
    initParameters(handlerMethod);

    thrown.expect(SnippetException.class);
    thrown.expectMessage(
            "Following path parameters were not documented: [id, subid, partId, yetAnotherId, optionalId]");

    new PathParametersSnippet().failOnUndocumentedParams(true).document(operationBuilder
            .attribute(HandlerMethod.class.getName(), handlerMethod)
            .attribute(JavadocReader.class.getName(), javadocReader)
            .attribute(ConstraintReader.class.getName(), constraintReader)
            .build());
}
 
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) {
    setRequestContext(request);
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    //判断当前请求是否为接口
    boolean hasResponseBody = method.isAnnotationPresent(ResponseBody.class);
    boolean hasRestController = handlerMethod.getBeanType().isAnnotationPresent(RestController.class);
    RequestContext requestContext = WebContextFacade.getRequestContext();
    requestContext.setApiRequest(hasResponseBody || hasRestController);
    WebContextFacade.setRequestContext(requestContext);
    return true;
}
 
源代码7 项目: sanshanblog   文件: UserAuthRestInterceptor.java
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    // 配置该注解,说明进行用户拦截
    WantUserToken annotation = handlerMethod.getBeanType().getAnnotation(WantUserToken.class);
    if (annotation==null){
        annotation = handlerMethod.getMethodAnnotation(WantUserToken.class);
    }
    //判断在网关处鉴权
    String token = request.getHeader(userAuthConfig.getTokenHeader());
    if (StringUtils.isEmpty(token)) {
        if (annotation == null) {
            return super.preHandle(request, response, handler);
        }
    }
    //进行拦截
    IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(token);
    UserContextHandler.setUsername(infoFromToken.getUsername());
    UserContextHandler.setUserID(infoFromToken.getId());
    return super.preHandle(request, response, handler);
}
 
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {
    HandlerMethod method = (HandlerMethod) handler;

    if (method.getMethodAnnotation(ResponseBody.class) == null) {
        CatnapResponseBody annotation = method.getMethodAnnotation(CatnapResponseBody.class);

        if (annotation != null) {
            String modelName = modelName(annotation, method);

            if (modelAndView != null) {
                //Transfer the model to a well known key so that we can retrieve it in the view.
                Object model = modelAndView.getModel().get(modelName);
                modelAndView.getModel().put(MODEL_NAME, model);
            }
        }
    }
}
 
@Test  // SPR-13318
public void jacksonSubType() throws Exception {
	Method method = JacksonController.class.getMethod("handleSubType");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	Object returnValue = new JacksonController().handleSubType();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertTrue(content.contains("\"id\":123"));
	assertTrue(content.contains("\"name\":\"foo\""));
}
 
@Test
public void saveModelAttributeToSession() throws Exception {
	TestController controller = new TestController();
	InitBinderBindingContext context = getBindingContext(controller);

	Method method = ResolvableMethod.on(TestController.class).annotPresent(GetMapping.class).resolveMethod();
	HandlerMethod handlerMethod = new HandlerMethod(controller, method);
	this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));

	WebSession session = this.exchange.getSession().block(Duration.ZERO);
	assertNotNull(session);
	assertEquals(0, session.getAttributes().size());

	context.saveModel();
	assertEquals(1, session.getAttributes().size());
	assertEquals("Bean", ((TestBean) session.getRequiredAttribute("bean")).getName());
}
 
@Test  // SPR-11225
public void resolveArgumentTypeVariableWithNonGenericConverter() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	HttpMessageConverter<Object> target = new MappingJackson2HttpMessageConverter();
	HttpMessageConverter<?> proxy = ProxyFactory.getProxy(HttpMessageConverter.class, new SingletonTargetSource(target));
	converters.add(proxy);
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
源代码12 项目: java-technology-stack   文件: ModelFactoryTests.java
@Test
public void sessionAttributeNotPresent() throws Exception {
	ModelFactory modelFactory = new ModelFactory(null, null, this.attributeHandler);
	HandlerMethod handlerMethod = createHandlerMethod("handleSessionAttr", String.class);
	try {
		modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod);
		fail("Expected HttpSessionRequiredException");
	}
	catch (HttpSessionRequiredException ex) {
		// expected
	}

	// Now add attribute and try again
	this.attributeStore.storeAttribute(this.webRequest, "sessionAttr", "sessionAttrValue");

	modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod);
	assertEquals("sessionAttrValue", this.mavContainer.getModel().get("sessionAttr"));
}
 
/**
 * Find search resource mappings.
 *
 * @param openAPI the open api
 * @param routerOperationList the router operation list
 * @param handlerMappingList the handler mapping list
 * @param domainType the domain type
 * @param resourceMetadata the resource metadata
 */
private void findSearchResourceMappings(OpenAPI openAPI, List<RouterOperation> routerOperationList, List<HandlerMapping> handlerMappingList, Class<?> domainType, ResourceMetadata resourceMetadata) {
	for (HandlerMapping handlerMapping : handlerMappingList) {
		if (handlerMapping instanceof RepositoryRestHandlerMapping) {
			RepositoryRestHandlerMapping repositoryRestHandlerMapping = (RepositoryRestHandlerMapping) handlerMapping;
			Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = repositoryRestHandlerMapping.getHandlerMethods();
			Map<RequestMappingInfo, HandlerMethod> handlerMethodMapFiltered = handlerMethodMap.entrySet().stream()
					.filter(requestMappingInfoHandlerMethodEntry -> REPOSITORY_SERACH_CONTROLLER.equals(requestMappingInfoHandlerMethodEntry
							.getValue().getBeanType().getName()))
					.filter(controller -> !AbstractOpenApiResource.isHiddenRestControllers(controller.getValue().getBeanType()))
					.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1));
			ResourceMetadata metadata = associations.getMetadataFor(domainType);
			SearchResourceMappings searchResourceMappings = metadata.getSearchResourceMappings();
			if (searchResourceMappings.isExported()) {
				findSearchControllers(routerOperationList, handlerMethodMapFiltered, resourceMetadata, domainType, openAPI, searchResourceMappings);
			}
		}
	}
}
 
源代码14 项目: bird-java   文件: IdempotencyInterceptor.java
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!(handler instanceof HandlerMethod)) return true;

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Idempotency idempotency = handlerMethod.getMethodAnnotation(Idempotency.class);
    if (idempotency == null) return true;

    String token = request.getHeader(this.headerName);
    if (StringUtils.isBlank(token)) {
        logger.warn("幂等性接口:{},请求头中token为空.", request.getRequestURI());
        if (idempotency.force()) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "该操作已失效,请刷新后重试");
            return false;
        }
        return true;
    }
    if (!CacheHelper.getCache().del(WebConstant.Cache.IDEMPOTENCY_NAMESPACE + token)) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "该操作已提交");
        return false;
    }

    return true;
}
 
@Test  // SPR-9964
public void resolveArgumentTypeVariable() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, mavContainer, webRequest, binderFactory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
源代码16 项目: youkefu   文件: UserInterceptorHandler.java
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 ; 
}
 
源代码17 项目: api-mock-util   文件: RequestMappingService.java
public boolean hasApiRegistered(String api,String requestMethod){
    notBlank(api,"api cant not be null");
    notBlank(requestMethod,"requestMethod cant not be null");

    RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for (RequestMappingInfo info : map.keySet()) {
        for(String pattern :info.getPatternsCondition().getPatterns()){
            if(pattern.equalsIgnoreCase(api)){ // 匹配url
                if(info.getMethodsCondition().getMethods().contains(getRequestMethod(requestMethod))){ // 匹配requestMethod
                    return true;
                }
            }
        }
    }

    return false;
}
 
源代码18 项目: spring-boot-plus   文件: UploadInterceptor.java
@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果访问的不是控制器,则跳出,继续执行下一个拦截器
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 访问路径
        String url = request.getRequestURI();
        // 访问全路径
        String fullUrl = request.getRequestURL().toString();
        // 上传拦截器,业务处理代码
        log.debug("UploadInterceptor...");
        // 访问token,如果需要,可以设置参数,进行鉴权
//        String token = request.getParameter(JwtTokenUtil.getTokenName());
        return true;
    }
 
源代码19 项目: rice   文件: UifControllerHandlerInterceptorTest.java
/**
 * Builds instance of a handler method (using the controller) for the given method to call.
 *
 * @param methodToCall method on controller to build handler for
 * @return handler method instance
 */
protected HandlerMethod getHandlerMethod(String methodToCall) {
    Method method = null;

    for (Method controllerMethod : controller.getClass().getMethods()) {
        if (StringUtils.equals(controllerMethod.getName(), methodToCall)) {
            method = controllerMethod;
        }
    }

    if (method != null) {
        return new HandlerMethod(controller, method);
    }

    return null;
}
 
源代码20 项目: RuoYi-Vue   文件: RepeatSubmitInterceptor.java
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
    if (handler instanceof HandlerMethod)
    {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation != null)
        {
            if (this.isRepeatSubmit(request))
            {
                AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
                ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
                return false;
            }
        }
        return true;
    }
    else
    {
        return super.preHandle(request, response, handler);
    }
}
 
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonView() throws Exception {
	String content = "{\"withView1\" : \"with\", \"withView2\" : \"with\", \"withoutView\" : \"without\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	Method method = JacksonController.class.getMethod("handleHttpEntity", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	HttpEntity<JacksonViewBean> result = (HttpEntity<JacksonViewBean>)
			processor.resolveArgument( methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
/**
 * Print the handler.
 */
protected void printHandler(@Nullable Object handler, @Nullable HandlerInterceptor[] interceptors)
		throws Exception {

	if (handler == null) {
		this.printer.printValue("Type", null);
	}
	else {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			this.printer.printValue("Type", handlerMethod.getBeanType().getName());
			this.printer.printValue("Method", handlerMethod);
		}
		else {
			this.printer.printValue("Type", handler.getClass().getName());
		}
	}
}
 
public MappingRegistration(T mapping, HandlerMethod handlerMethod,
		@Nullable List<String> directUrls, @Nullable String mappingName) {

	Assert.notNull(mapping, "Mapping must not be null");
	Assert.notNull(handlerMethod, "HandlerMethod must not be null");
	this.mapping = mapping;
	this.handlerMethod = handlerMethod;
	this.directUrls = (directUrls != null ? directUrls : Collections.emptyList());
	this.mappingName = mappingName;
}
 
@Test
public void resolveExceptionWithAssertionErrorAsRootCause() throws Exception {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
	this.resolver.setApplicationContext(ctx);
	this.resolver.afterPropertiesSet();

	AssertionError err = new AssertionError("argh");
	FatalBeanException ex = new FatalBeanException("wrapped", err);
	HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
	ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);

	assertNotNull("Exception was not handled", mav);
	assertTrue(mav.isEmpty());
	assertEquals(err.toString(), this.response.getContentAsString());
}
 
源代码25 项目: spring-auto-restdocs   文件: SectionSnippetTest.java
@Test
public void customSnippets() throws Exception {
    HandlerMethod handlerMethod = new HandlerMethod(new TestResource(), "getItem");
    mockMethodTitle(TestResource.class, "getItem", "");

    new SectionBuilder()
            .snippetNames(HTTP_RESPONSE, AUTO_RESPONSE_FIELDS, HTTP_REQUEST)
            .build()
            .document(operationBuilder
                    .attribute(HandlerMethod.class.getName(), handlerMethod)
                    .attribute(JavadocReader.class.getName(), javadocReader)
                    .attribute(ATTRIBUTE_NAME_DEFAULT_SNIPPETS, Arrays.asList(
                            pathParameters(), requestParameters(),
                            requestFields(), responseFields(), curlRequest(),
                            HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse()))
                    .request("http://localhost/items/1")
                    .build());

    assertThat(this.generatedSnippets.snippet(SECTION))
            .isEqualTo(fixLineSeparator(
                    "[[resources-customSnippets]]\n" +
                            "=== Get Item\n\n" +
                            "include::auto-method-path.adoc[]\n\n" +
                            "include::auto-description.adoc[]\n\n" +
                            "==== Example response\n\n" +
                            "include::http-response.adoc[]\n\n" +
                            "==== Response fields\n\n" +
                            "include::auto-response-fields.adoc[]\n\n" +
                            "==== Example request\n\n" +
                            "include::http-request.adoc[]\n"));
}
 
@Override
protected Type getType(HandlerMethod method) {
    if (requestBodyType != null) {
        return requestBodyType;
    }

    for (MethodParameter param : method.getMethodParameters()) {
        if (isRequestBody(param)) {
            return getType(param);
        }
    }
    return null;
}
 
@Test
public void handleAndValidateRequestBody() throws Exception {
	Class<?>[] parameterTypes = new Class<?>[] { TestBean.class, Errors.class };

	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.setContent("Hello Server".getBytes("UTF-8"));

	HandlerMethod handlerMethod = handlerMethod("handleAndValidateRequestBody", parameterTypes);

	ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod);

	assertNull(mav);
	assertEquals("Error count [1]", new String(response.getContentAsByteArray(), "UTF-8"));
	assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus());
}
 
@Test  // SPR-16496
public void resolveExceptionControllerAdviceAgainstProxy() throws Exception {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class);
	this.resolver.setApplicationContext(ctx);
	this.resolver.afterPropertiesSet();

	IllegalStateException ex = new IllegalStateException();
	HandlerMethod handlerMethod = new HandlerMethod(new ProxyFactory(new ResponseBodyController()).getProxy(), "handle");
	ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);

	assertNotNull("Exception was not handled", mav);
	assertTrue(mav.isEmpty());
	assertEquals("BasePackageTestExceptionResolver: IllegalStateException", this.response.getContentAsString());
}
 
源代码29 项目: admin-plus   文件: UrlInterceptor.java
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	try {
		HttpSession session = request.getSession();
		String path = request.getServletPath();
		User user = (User) session.getAttribute(Const.SESSION_USER);
		if (null == user || "".equals(user)) {
			response.sendRedirect("/");
			return false;
		} else {
			path = path.substring(1, path.length());
			boolean b = Jurisdiction.hasJurisdiction(path, session);
			if (!b) {
				response.sendRedirect("/error/404");
				return b;
			}
		}

		//是否有权限
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			//获取controller注解, controller检查是否有权限控制
			Permission permission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Permission.class);
			if(!checkPermission(permission,request)){
				outputJson(response, new ResponseModel(ApiResultEnum.AUTH_NOT_HAVE,null));
				return false;
			}
			//获取方法注解,方法检查是否有权限控制
			permission = handlerMethod.getMethod().getAnnotation(Permission.class);
			if(!checkPermission(permission,request)){
				outputJson(response, new ResponseModel(ApiResultEnum.AUTH_NOT_HAVE,null));
				return false;
			}
		}

	} catch (Exception e) {
		e.printStackTrace();
	}
	return true;
}
 
@Override
protected void enrichModel(Map<String, Object> model, HandlerMethod handlerMethod,
        FieldDescriptors fieldDescriptors, SnippetTranslationResolver translationResolver) {
    model.put("isPageResponse", isPageResponse(handlerMethod));
    if (fieldDescriptors.getNoContentMessageKey() != null) {
        model.put("no-response-body", translationResolver.translate(fieldDescriptors.getNoContentMessageKey()));
    }
}