利用ThreadLocal管理request和session以及用户信息,实现 Use anywhere

1.我们有时需要获取request或session中的数据的时候,首先需要获取request和session对象,这个通常是在Controller的时候当做入参获取,这样方法的入参会显得很长很臃肿的感觉。这就是的出发点,接下来就展示一下是如何实现的。


2.首先我们写个一个拦截器:WebContextFilter

package com.office.common.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.office.common.context.WebContextHolder;

/**
 * webcontent信息加载到TheadLocal中
 * @author Neo
 * @date 2017年10月20日11:38:45
 */
public class WebContextFilter extends OncePerRequestFilter {

	public WebContextFilter() {
	}

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (request == null || response == null) {
			return;
		} else {
			WebContextHolder.setRequest(request);
			WebContextHolder.setResponse(response);
			filterChain.doFilter(request, response);
			return;
		}
	}
}

3.然后我们将写好的拦截器配置到web.xml中:



	
	Archetype Created Web Application

	
		contextConfigLocation
		
	

	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	
	
		encodingFilter
		/*
	
	
	
	
	
	
		webContentFilter
		com.office.common.filter.WebContextFilter
	
	
		webContentFilter
		/*
	
	
		org.springframework.web.context.ContextLoaderListener
	
	

	
		springMVC
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath*:applicationContext.xml
		
		1
	
	
		springMVC
		/
	


4.编写一个同一个管理操作工具类:WebContextHolder

package com.office.common.context;

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

import com.office.common.dto.UserDTO;

/**
 * 上下文
 * @author Neo
 * @date 2017年10月20日11:42:57
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class WebContextHolder {

	public WebContextHolder() {
	}

	public static String getRequestIp() {
		if (getRequest() == null)
			return null;
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
				ip = request.getHeader("Proxy-Client-IP");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
				ip = request.getHeader("WL-Proxy-Client-IP");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
				ip = request.getHeader("HTTP_CLIENT_IP");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
				ip = request.getRemoteAddr();
		} else if (ip.length() > 15) {
			String ips[] = ip.split(",");
			int index = 0;
			do {
				if (index >= ips.length)
					break;
				String strIp = ips[index];
				if (!"unknown".equalsIgnoreCase(strIp)) {
					ip = strIp;
					break;
				}
				index++;
			} while (true);
		}
		return ip;
	}

	public static HttpServletRequest getRequest() {
		if (requestLocal == null)
			return null;
		else
			return (HttpServletRequest) requestLocal.get();
	}

	public static String getContextPath() {
		if (getRequest() == null)
			return null;
		else
			return (new StringBuilder()).append(getRequest().getContextPath()).append("/").toString();
	}

	public static String getCurrRequestURI() {
		if (getRequest() == null)
			return null;
		else
			return (new StringBuilder()).append(getRequest().getRequestURI().replace(getRequest().getContextPath(), ""))
					.append("/").toString();
	}

	public static HttpServletResponse getResponse() {
		if (responseLocal == null)
			return null;
		else
			return (HttpServletResponse) responseLocal.get();
	}

	public static HttpSession getSession() {
		if (requestLocal == null)
			return null;
		if (requestLocal.get() == null)
			return null;
		else
			return ((HttpServletRequest) requestLocal.get()).getSession();
	}

	public static UserDTO getLoginUserSession(Class loginUserClass) {
		if (getSession() == null)
			return null;
		Object obj = getSession().getAttribute(CURRENT_USER);
		if (obj == null)
			return null;
		else
			return (UserDTO) obj;
	}

	public static UserDTO getLoginUserSession() {
		return getLoginUserSession(UserDTO.class);
	}

	public static void createLoginUserSession(UserDTO loginUser) {
		if (loginUser != null)
			getSession().setAttribute(CURRENT_USER, loginUser);
	}

	public static void destroyLoginUserSession() {
		if (getLoginUserSession() != null) {
			getSession().removeAttribute(CURRENT_USER);
			getSession().invalidate();
		}
	}

	public static void setRequest(HttpServletRequest request) {
		if (requestLocal == null)
			requestLocal = new ThreadLocal();
		requestLocal.set(request);
	}

	public static void setResponse(HttpServletResponse response) {
		if (responseLocal == null)
			responseLocal = new ThreadLocal();
		responseLocal.set(response);
	}
	
	
    /**
     * 获取项目请求的根目录
     * 
     * @return eg:http://localhost:8080/projectName
     */
	public static String getProjectRequestRootPath() {
		HttpServletRequest request = WebContextHolder.getRequest();
		StringBuffer sb = new StringBuffer();
		sb.append(request.getScheme()).
		   append("://").
		   append(request.getServerName()).
		   append(":").
		   append(request.getServerPort()).
		   append(request.getContextPath()).
		   append("/");
		return sb.toString();
	}

	private static ThreadLocal requestLocal;
	private static ThreadLocal responseLocal;
	public static String CURRENT_USER = "CURRENT_USER";

}

5.使用展示:

		//我们可以在任何地方使用这种方法取值
		WebContextHolder.getRequest().getParameter("id");



你可能感兴趣的:(java,Spring)