package com.github.wxiaoqi.security.common.util;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 获取request中的参数
 */
public class RequestContextHolderUtil {

	public static HttpServletRequest getRequest() {
		return getRequestAttributes().getRequest();
	}

	public static HttpServletResponse getResponse() {
		return getRequestAttributes().getResponse();
	}

	public static HttpSession getSession(boolean create) {
		return getRequest().getSession(create);
	}

	public static HttpSession getSession() {
		return getSession(true);
	}

	public static String getRequestParameter(String name) {
		return getRequest().getParameter(name);
	}

	public static ServletRequestAttributes getRequestAttributes() {
		RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		return ((ServletRequestAttributes) requestAttributes);
	}

	public static ServletContext getServletContext() {
		return ContextLoader.getCurrentWebApplicationContext().getServletContext();
	}

	public static String getRequestHeader(String name) {
		return getRequest().getHeader(name);
	}

	public static String getBaseUrl() {
		HttpServletRequest request = getRequest();
		StringBuffer requestURL = request.getRequestURL();
		String url = requestURL.delete(requestURL.length() - request.getRequestURI().length(), requestURL.length())
				.toString();
		return url;
	}

}