Java Code Examples for org.springframework.web.context.request.RequestAttributes

The following examples show how to use org.springframework.web.context.request.RequestAttributes. These examples are extracted from open source projects. 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 Project: keycloak   Source File: AdminController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "/SessionServlet", method = RequestMethod.GET)
public String sessionServlet(WebRequest webRequest, Model model) {
 String counterString = (String) webRequest.getAttribute("counter", RequestAttributes.SCOPE_SESSION);
 int counter = 0;
 try {
     counter = Integer.parseInt(counterString, 10);
    }
    catch (NumberFormatException ignored) {
    }

    model.addAttribute("counter", counter);

 webRequest.setAttribute("counter", Integer.toString(counter+1), RequestAttributes.SCOPE_SESSION);

 return "session";
}
 
Example 2
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
                              NativeWebRequest webRequest) throws Exception {
    mavContainer.setRequestHandled(true);
    HttpServletResponse httpServletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
    httpServletResponse.setContentType(CONTENT_TYPE);
    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(httpServletResponse);
    Locale locale = (Locale)webRequest.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
        RequestAttributes.SCOPE_SESSION);
    String message;
    try {
        message = messageSource.getMessage(DEFAULT_SUCCESS_CODE, new Object[0], locale);
    } catch (NoSuchMessageException e) {
        message = DefaultMessagesProperties.getMessage(DEFAULT_SUCCESS_CODE);
    }
    JsonResponse jsonResponse = new JsonResponse(DEFAULT_SUCCESS_CODE, message, returnValue);
    outputMessage.getBody().write(StringUtils.toBytes(JsonUtils.toJson(jsonResponse)));
    outputMessage.getBody().flush();
}
 
Example 3
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
	RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
	Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
	List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
	if (requestedMediaTypes != null) {
		List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
		View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);
		if (bestView != null) {
			return bestView;
		}
	}
	if (this.useNotAcceptableStatusCode) {
		if (logger.isDebugEnabled()) {
			logger.debug("No acceptable view found; returning 406 (Not Acceptable) status code");
		}
		return NOT_ACCEPTABLE_VIEW;
	}
	else {
		logger.debug("No acceptable view found; returning null");
		return null;
	}
}
 
Example 4
@Override
public Object interceptor(final ProceedingJoinPoint pjp) throws Throwable {
    HmilyTransactionContext hmilyTransactionContext = HmilyTransactionContextLocal.getInstance().get();
    if (Objects.nonNull(hmilyTransactionContext)) {
        if (HmilyRoleEnum.START.getCode() == hmilyTransactionContext.getRole()) {
            hmilyTransactionContext.setRole(HmilyRoleEnum.SPRING_CLOUD.getCode());
        }
    } else {
        try {
            final RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            hmilyTransactionContext = RpcMediator.getInstance().acquire(key -> {
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                return request.getHeader(key);
            });
        } catch (IllegalStateException ex) {
            LogUtil.warn(LOGGER, () -> "can not acquire request info:" + ex.getLocalizedMessage());
        }
    }
    return hmilyTransactionAspectService.invoke(hmilyTransactionContext, pjp);
}
 
Example 5
Source Project: sinavi-jfw   Source File: PostBackManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 現在のリクエストに対してポストバック機構を開始します。
 * </p>
 * @param request リクエスト
 * @param handlerMethod ハンドラ
 */
public static void begin(HttpServletRequest request, HandlerMethod handlerMethod) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    PostBackManager instance = new PostBackManager(request , handlerMethod);
    requestAttributes.setAttribute(STORE_KEY_TO_REQUEST, instance, RequestAttributes.SCOPE_REQUEST);
    MessageContext messageContext = (MessageContext) requestAttributes.getAttribute(MessageContext.MESSAGE_CONTEXT_ATTRIBUTE_KEY, RequestAttributes.SCOPE_REQUEST);
    if (messageContext == null) {
        requestAttributes.setAttribute(MessageContext.MESSAGE_CONTEXT_ATTRIBUTE_KEY, new MessageContext(request), RequestAttributes.SCOPE_REQUEST);
    }
    instance.targetControllerType = handlerMethod.getBeanType();
    for (MethodParameter methodParameter : handlerMethod.getMethodParameters()) {
        ModelAttribute attr = methodParameter.getParameterAnnotation(ModelAttribute.class);
        if (attr != null) {
            instance.modelAttributeType = methodParameter.getParameterType();
        }
    }
}
 
Example 6
Source Project: sophia_scaffolding   Source File: ApiLogAspect.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <方法执行前>
 *
 * @param point  [参数说明]
 * @param sysLog sysLog
 * @return void [返回类型说明]
 * @see [类、类#方法、类#成员]
 */
@Before(value = "log()")
public void before(JoinPoint point) throws Throwable {
    ApiLogger apiLogger = new ApiLogger();
    //将当前实体保存到threadLocal
    log.info("日志开始记录");
    logThreadLocal.set(apiLogger);
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();
    String operation = request.getMethod();
    apiLogger.setId(UuidUtil.getUuid());
    apiLogger.setCreateTime(LocalDateTime.now());
    if (!request.getRequestURI().contains(GlobalsConstants.LOGIN)) {
        apiLogger.setUserName(getUsername());
        apiLogger.setParams(Arrays.toString(point.getArgs()));
    }
    apiLogger.setMethodName(getMethodDescription(point) + ":" + point.getSignature().getName());
    apiLogger.setClassName(point.getTarget().getClass().getName());
    apiLogger.setMethod(operation);
    apiLogger.setUri(URLUtil.getPath(request.getRequestURI()));
    apiLogger.setIp(getIpAddr(request));
    apiLogger.setServiceId(getClientId());
    log.info("结束日志记录");
}
 
Example 7
Source Project: Spring-Boot-I18n-Pro   Source File: MessageResourceExtension.java    License: MIT License 6 votes vote down vote up
@Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
    // 获取request中设置的指定国际化文件名
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    final String i18File = (String) attr.getAttribute(I18N_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    if (!StringUtils.isEmpty(i18File)) {
        //获取在basenameSet中匹配的国际化文件名
        String basename = getBasenameSet().stream()
                .filter(name -> StringUtils.endsWithIgnoreCase(name, i18File))
                .findFirst().orElse(null);
        if (!StringUtils.isEmpty(basename)) {
            //得到指定的国际化文件资源
            ResourceBundle bundle = getResourceBundle(basename, locale);
            if (bundle != null) {
                return getStringOrNull(bundle, code);
            }
        }
    }
    //如果指定i18文件夹中没有该国际化字段,返回null会在ParentMessageSource中查找
    return null;
}
 
Example 8
private static WebApplicationContext getWebApplicationContext() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes == null) {
		logger.debug("No request bound to the current thread: is DispatcherSerlvet used?");
		return null;
	}

	HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
	if (request == null) {
		logger.debug("Request bound to current thread is not an HttpServletRequest");
		return null;
	}

	String attributeName = DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	WebApplicationContext wac = (WebApplicationContext) request.getAttribute(attributeName);
	if (wac == null) {
		logger.debug("No WebApplicationContext found: not in a DispatcherServlet request?");
		return null;
	}
	return wac;
}
 
Example 9
Source Project: SpringBoot-Dubbo-Docker-Jenkins   Source File: LogHandle.java    License: Apache License 2.0 6 votes vote down vote up
@Around("restLog()")
public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {

    // 生成本次请求时间戳
    String timestamp = System.currentTimeMillis()+"";

    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();

    String url = request.getRequestURL().toString();
    String method = request.getMethod();
    String uri = request.getRequestURI();
    String queryString = request.getQueryString();
    logger.info(timestamp + ", url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = joinPoint.proceed();
    logger.info(timestamp + " , " + result.toString());
}
 
Example 10
Source Project: zhcet-web   Source File: StudentRegistrationController.java    License: Apache License 2.0 6 votes vote down vote up
@PostMapping("/confirm")
public String uploadStudents(RedirectAttributes attributes,
                             @SessionAttribute(KEY_STUDENT_REGISTRATION) Confirmation<Student> confirmation,
                             WebRequest webRequest) {
    if (confirmation == null || !confirmation.getErrors().isEmpty()) {
        attributes.addFlashAttribute("errors", Collections.singletonList("Unknown Error"));
    } else {
        try {
            RealTimeStatus status = realTimeStatusService.install();
            studentUploadService.registerStudents(confirmation, status);
            attributes.addFlashAttribute("task_id_student", status.getId());
            attributes.addFlashAttribute("students_registered", true);
        } catch (Exception e) {
            log.error("Error registering students", e);
            attributes.addFlashAttribute("student_unknown_error", true);
        }

        webRequest.removeAttribute(KEY_STUDENT_REGISTRATION, RequestAttributes.SCOPE_SESSION);
    }

    return "redirect:/admin/dean";
}
 
Example 11
Source Project: onetwo   Source File: WebAttributeArgumentResolver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
	Object result = null;
	WebAttribute attrAnnotation = parameter.getParameterAnnotation(WebAttribute.class);
	String attrName = attrAnnotation.value();
	if(StringUtils.isBlank(attrName))
		return result;
	result = webRequest.getAttribute(attrName, RequestAttributes.SCOPE_REQUEST);
	result = (result==null)?webRequest.getAttribute(attrName, RequestAttributes.SCOPE_SESSION):result;
	return result;
}
 
Example 12
Source Project: phoenix   Source File: DataController.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpServletRequest getCurrentRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
    Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
    HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
    Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
    return servletRequest;
}
 
Example 13
Source Project: spring-cloud-yes   Source File: MyErrorController.java    License: Apache License 2.0 5 votes vote down vote up
private Throwable getException(HttpServletRequest request) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    Throwable exception = getAttribute(
            requestAttributes,
            ERROR_ATTRIBUTE
    );

    if (exception == null) {
        exception = getAttribute(requestAttributes, "javax.servlet.error.exception");
    }
    return exception;
}
 
Example 14
Source Project: audit4j-spring   Source File: WebSessionAuditMetaData.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @see org.audit4j.core.MetaData#getActor()
 * 
 */
@Override
public String getActor() {
    String actor = (String) RequestContextHolder.currentRequestAttributes()
            .getAttribute(actorSessionAttribute, RequestAttributes.SCOPE_SESSION);
    if (actor != null) {
        return actor;
    }
    return undefienedActorName;
}
 
Example 15
Source Project: data-prep   Source File: HttpRequestContext.java    License: Apache License 2.0 5 votes vote down vote up
public static Enumeration<String> parameters() {
    final RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
    if (attributes != null && attributes instanceof ServletRequestAttributes) {
        return ((ServletRequestAttributes) attributes).getRequest().getParameterNames();
    }
    return Collections.emptyEnumeration();
}
 
Example 16
@Override
@SuppressWarnings("unchecked")
@Nullable
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
	Map<String, String> uriTemplateVars = (Map<String, String>) request.getAttribute(
			HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
	return (uriTemplateVars != null ? uriTemplateVars.get(name) : null);
}
 
Example 17
Source Project: restdocs-raml   Source File: ExceptionSupressingErrorAttributes.java    License: MIT License 5 votes vote down vote up
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
		boolean includeStackTrace) {
	Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
	errorAttributes.remove("exception");
	Object message = requestAttributes.getAttribute("javax.servlet.error.message", RequestAttributes.SCOPE_REQUEST);
	if (message != null) {
		errorAttributes.put("message", message);
	}
	return errorAttributes;
}
 
Example 18
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	@SuppressWarnings("unchecked")
	Map<String, MultiValueMap<String, String>> matrixVariables =
			(Map<String, MultiValueMap<String, String>>) request.getAttribute(
					HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

	if (CollectionUtils.isEmpty(matrixVariables)) {
		return Collections.emptyMap();
	}

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	MatrixVariable ann = parameter.getParameterAnnotation(MatrixVariable.class);
	Assert.state(ann != null, "No MatrixVariable annotation");
	String pathVariable = ann.pathVar();

	if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
		MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
		if (mapForPathVariable == null) {
			return Collections.emptyMap();
		}
		map.putAll(mapForPathVariable);
	}
	else {
		for (MultiValueMap<String, String> vars : matrixVariables.values()) {
			vars.forEach((name, values) -> {
				for (String value : values) {
					map.add(name, value);
				}
			});
		}
	}

	return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}
 
Example 19
@Override
public String getLocalDispatcherUrl() {
	if (localDispatcherUrl == null) {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
		return getBasePathForHostNamePort(request, request.getLocalName(), request.getLocalPort());
	} else {
		return localDispatcherUrl;
	}
}
 
Example 20
Source Project: spring-analysis-note   Source File: MvcUriComponentsBuilder.java    License: MIT License 5 votes vote down vote up
@Nullable
private static WebApplicationContext getWebApplicationContext() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes == null) {
		return null;
	}
	HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
	String attributeName = DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	WebApplicationContext wac = (WebApplicationContext) request.getAttribute(attributeName);
	if (wac == null) {
		return null;
	}
	return wac;
}
 
Example 21
@Override
public void run() {
    RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(requestAttributes);
    try {
        delegate.run();
    } finally {
        RequestContextHolder.setRequestAttributes(previousRequestAttributes);
    }
}
 
Example 22
Source Project: java-technology-stack   Source File: WebApplicationContextUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return the current RequestAttributes instance as ServletRequestAttributes.
 * @see RequestContextHolder#currentRequestAttributes()
 */
private static ServletRequestAttributes currentRequestAttributes() {
	RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
	if (!(requestAttr instanceof ServletRequestAttributes)) {
		throw new IllegalStateException("Current request is not a servlet request");
	}
	return (ServletRequestAttributes) requestAttr;
}
 
Example 23
Source Project: java-technology-stack   Source File: WebAsyncUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Obtain the {@link WebAsyncManager} for the current request, or if not
 * found, create and associate it with the request.
 */
public static WebAsyncManager getAsyncManager(WebRequest webRequest) {
	int scope = RequestAttributes.SCOPE_REQUEST;
	WebAsyncManager asyncManager = null;
	Object asyncManagerAttr = webRequest.getAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, scope);
	if (asyncManagerAttr instanceof WebAsyncManager) {
		asyncManager = (WebAsyncManager) asyncManagerAttr;
	}
	if (asyncManager == null) {
		asyncManager = new WebAsyncManager();
		webRequest.setAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, asyncManager, scope);
	}
	return asyncManager;
}
 
Example 24
Source Project: spring-analysis-note   Source File: WebAsyncUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Obtain the {@link WebAsyncManager} for the current request, or if not
 * found, create and associate it with the request.
 */
public static WebAsyncManager getAsyncManager(WebRequest webRequest) {
	int scope = RequestAttributes.SCOPE_REQUEST;
	WebAsyncManager asyncManager = null;
	Object asyncManagerAttr = webRequest.getAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, scope);
	if (asyncManagerAttr instanceof WebAsyncManager) {
		asyncManager = (WebAsyncManager) asyncManagerAttr;
	}
	if (asyncManager == null) {
		asyncManager = new WebAsyncManager();
		webRequest.setAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, asyncManager, scope);
	}
	return asyncManager;
}
 
Example 25
private ServletRequestAttributes getRequestAttributes()
{
	final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes instanceof ServletRequestAttributes)
	{
		return (ServletRequestAttributes)requestAttributes;
	}
	else
	{
		throw new IllegalStateException("Not called in the context of an HTTP request (" + requestAttributes + ")");
	}
}
 
Example 26
Source Project: onetwo   Source File: RequestContextConcurrencyStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
		public T call() throws Exception {
			RequestAttributes existRequestAttributes = RequestContextHolder.getRequestAttributes();
			//当前线程的attrs和代理的不一致,则需要重置
			boolean needToSetContext = authEnv!=null && authEnv.getRequestAttributes()!=null && !authEnv.getRequestAttributes().equals(existRequestAttributes);
//			boolean hasOauth2Ctx = StringUtils.isNotBlank(authorizationToken);
			try {
				/*RequestContextHolder.setRequestAttributes(delegateRequestAttributes);
				if (hasOauth2Ctx) {
					OAuth2Utils.setCurrentToken(authorizationToken);
				}
				AuthEnvs.setCurrent(authEnv);*/
				if (authEnv!=null) {
					if (needToSetContext) {
						RequestContextHolder.setRequestAttributes(authEnv.getRequestAttributes());
					}
					AuthEnvs.setCurrent(authEnv);
				}
				return this.delegate.call();
			} finally {
				/*if (hasOauth2Ctx) {
					OAuth2Utils.removeCurrentToken();
				}
				*/
				if (authEnv!=null) {
					AuthEnvs.removeCurrent();
				}
				if (needToSetContext){
					RequestContextHolder.setRequestAttributes(existRequestAttributes);
				}
			}
		}
 
Example 27
@Test
public void testSetRequestScopedAttribute() throws Exception {
	MockPortletRequest request = new MockPortletRequest();
	PortletRequestAttributes attrs = new PortletRequestAttributes(request);
	attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
	Object value = request.getAttribute(KEY);
	assertSame(VALUE, value);
}
 
Example 28
@Test
public void testSetGlobalSessionScopedAttributeAfterCompletion() throws Exception {
	MockPortletSession session = new MockPortletSession();
	session.setAttribute(KEY, VALUE);
	MockPortletRequest request = new MockPortletRequest();
	request.setSession(session);
	PortletRequestAttributes attrs = new PortletRequestAttributes(request);
	attrs.requestCompleted();
	request.close();
	attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION);
	Object value = session.getAttribute(KEY);
	assertSame(VALUE, value);
}
 
Example 29
Source Project: controller-logger   Source File: RequestUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private HttpServletRequest getCurrentHttpRequest() {
    HttpServletRequest request = null;
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
        request = ((ServletRequestAttributes)requestAttributes).getRequest();
    }
    return request;
}
 
Example 30
Source Project: mogu_blog_v2   Source File: RequestHolder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取session的Attribute
 *
 * @param name session的key
 * @return Object
 */
public static Object getSession(String name) {
    log.debug("getSession -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName());
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
    if (null == servletRequestAttributes) {
        return null;
    }
    return servletRequestAttributes.getAttribute(name, RequestAttributes.SCOPE_SESSION);
}