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

The following examples show how to use org.springframework.web.context.request.RequestAttributes. 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: MessageResourceExtension.java    From Spring-Boot-I18n-Pro with 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 #2
Source File: ContentNegotiatingViewResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: JsonHandlerMethodReturnValueHandler.java    From sca-best-practice with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: SpringCloudHmilyTransactionInterceptor.java    From hmily with Apache License 2.0 6 votes vote down vote up
@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 File: StudentRegistrationController.java    From zhcet-web with 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 #6
Source File: PostBackManager.java    From sinavi-jfw with 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 #7
Source File: ApiLogAspect.java    From sophia_scaffolding with 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 #8
Source File: LogHandle.java    From SpringBoot-Dubbo-Docker-Jenkins with 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 #9
Source File: MvcUriComponentsBuilder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: AdminController.java    From keycloak with 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 #11
Source File: CatnapViewResolverTest.java    From catnap with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveViewByInvalidHrefSuffixReturnsNull() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    requestAttributes.setAttribute(RequestAttributes.REFERENCE_REQUEST, request, RequestAttributes.SCOPE_REQUEST);
    RequestContextHolder.setRequestAttributes(requestAttributes);

    assertNull(viewResolver.resolveViewName("/view.xml", Locale.US));
}
 
Example #12
Source File: ServletWebArgumentResolverAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected NativeWebRequest getWebRequest() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	Assert.state(requestAttributes instanceof ServletRequestAttributes, "No ServletRequestAttributes");
	ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
	return new ServletWebRequest(servletRequestAttributes.getRequest());
}
 
Example #13
Source File: AuthEnvs.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static AuthEnv getCurrent() {
	RequestAttributes req = RequestContextHolder.getRequestAttributes();
	if (req!=null) {
		return (AuthEnv) req.getAttribute(AUTH_ENV_KEY, RequestAttributes.SCOPE_REQUEST);
	} else {
		return CURRENT_ENVS.get();
	}
}
 
Example #14
Source File: SecureUtil.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取request
 *
 * @return request
 */
private HttpServletRequest getRequest() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if ((requestAttributes == null)) {
		throw new SecureException("There is not web environment!");
	}
	return ((ServletRequestAttributes) requestAttributes).getRequest();
}
 
Example #15
Source File: RequestHolder.java    From springboot-shiro with MIT License 5 votes vote down vote up
/**
 * 添加session
 *
 * @param name
 * @param value
 */
public static void setSession(String name, Object value) {
    log.debug("setSession -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName());
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
    if (null == servletRequestAttributes) {
        return;
    }
    servletRequestAttributes.setAttribute(name, value, RequestAttributes.SCOPE_SESSION);
}
 
Example #16
Source File: BaseServerController.java    From Jpom with MIT License 5 votes vote down vote up
public static UserModel getUserModel() {
    ServletRequestAttributes servletRequestAttributes = tryGetRequestAttributes();
    if (servletRequestAttributes == null) {
        return null;
    }
    return (UserModel) servletRequestAttributes.getAttribute(LoginInterceptor.SESSION_NAME, RequestAttributes.SCOPE_SESSION);
}
 
Example #17
Source File: CurrentTenantIdentifierResolverImpl.java    From multitenancy with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String resolveCurrentTenantIdentifier() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes != null) {
		String identifier = (String) requestAttributes.getAttribute("CURRENT_TENANT_IDENTIFIER",RequestAttributes.SCOPE_REQUEST);
		if (identifier != null) {
			return identifier;
		}
	}
	return DEFAULT_TENANT_ID;
}
 
Example #18
Source File: RequestHolder.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 清除指定session
 *
 * @param name
 * @return void
 */
public static void removeSession(String name) {
    log.debug("removeSession -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName());
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
    if (null == servletRequestAttributes) {
        return;
    }
    servletRequestAttributes.removeAttribute(name, RequestAttributes.SCOPE_SESSION);
}
 
Example #19
Source File: ServletWebArgumentResolverAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected NativeWebRequest getWebRequest() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes instanceof ServletRequestAttributes) {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
		return new ServletWebRequest(servletRequestAttributes.getRequest());
	}
	return null;
}
 
Example #20
Source File: RequestHolder.java    From mogu_blog_v2 with 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);
}
 
Example #21
Source File: RequestUtil.java    From controller-logger with 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 #22
Source File: PortletRequestAttributesTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: PortletRequestAttributesTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: MatrixVariableMapMethodArgumentResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest request, 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<String, String>();
	String pathVariable = parameter.getParameterAnnotation(MatrixVariable.class).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()) {
			for (String name : vars.keySet()) {
				for (String value : vars.get(name)) {
					map.add(name, value);
				}
			}
		}
	}

	return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}
 
Example #25
Source File: RequestContextConcurrencyStrategy.java    From onetwo with 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 #26
Source File: HostKeyConfig.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
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 #27
Source File: ReactiveTypeHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Collection<MediaType> getMediaTypes(NativeWebRequest request)
		throws HttpMediaTypeNotAcceptableException {

	Collection<MediaType> mediaTypes = (Collection<MediaType>) request.getAttribute(
			HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

	return CollectionUtils.isEmpty(mediaTypes) ?
			this.contentNegotiationManager.resolveMediaTypes(request) : mediaTypes;
}
 
Example #28
Source File: WebuiExceptionHandler.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private void addPath(final Map<String, Object> errorAttributes, final RequestAttributes requestAttributes)
{
	final String path = getAttribute(requestAttributes, RequestDispatcher.ERROR_REQUEST_URI);
	if (path != null)
	{
		errorAttributes.put(ATTR_Path, path);
	}
}
 
Example #29
Source File: MatrixVariableMapMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #30
Source File: AutomaticDispatcherUrlService.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getDispatcherUrl() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (null == requestAttributes || !(requestAttributes instanceof ServletRequestAttributes)) {
		log.warn("Trying to automatically get the dispatcher URL, but not running inside a servlet request. " +
				"You are recommended to use StaticDispatcherUrlService");
		return "./d/"; // use relative URL as back-up, will fail in many cases
	}

	HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

	String serverName = request.getServerName();

	// X-Forwarded-Host if behind a reverse proxy, fallback to general method.
	// Alternative we could use the gwt module url to guess the real URL.
	if (null != request.getHeader(X_FORWARD_HOST_HEADER)) {
		log.warn("AutomaticDispatcherService detected a X-Forwarded-Host header which means the server is " +
				"accessed using a reverse proxy server. This might cause problems in some cases. You are " +
				"recommended to configure your tomcat connector to be aware of the original url. " +
				"(see http://tomcat.apache.org/tomcat-6.0-doc/proxy-howto.html )");
		String gwtModuleBase = request.getHeader(X_GWT_MODULE_HEADER);
		if (null != gwtModuleBase) {
			// Get last slash in the gwtModuleBase, ignoring the trailing slash.
			int contextEndIndex = gwtModuleBase.lastIndexOf("/", gwtModuleBase.length() - 2);
			if (contextEndIndex > -1) {
				return gwtModuleBase.substring(0, contextEndIndex) + "/d/";
			}
		} else {
			// else get the information from the X-forwarded-host header and default to the standard behaviour 
			serverName = request.getHeader(X_FORWARD_HOST_HEADER);
		}
	}

	return getBasePathForHostNamePort(request, serverName, request.getServerPort());
}