Spring MVC 4 獲取 Request 和 Reponse 對象方法

這裏主要說一下在非Controller層中如何獲取Response對象的方法,以前在項目開發過程當中,第三方類庫須要用到Response對象,因而度娘尋找如何獲取該對象,有如下幾種方式都不行,沒有去查源碼,應該是reponse對象沒有再被暴露出來,順道貼一下網上的方法。java

1. 經過spring提供的RequestContextHolder在非contrller層獲取request和response對象spring

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();

HttpServletResponse response = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();

ServletContext context = ContextLoader.getCurrentWebApplicationContext().getServletContext();

    該方法不必定有效,根據Spring版本自行尋找問題,如今要說的是另一種通用的方法。ide

2.經過攔截器加載線程的方式線程

這個文件用於加載線程,同時建立、獲取、設置、移除HttpServletRequest和HttpServletResponse對象。code

/**
 * 根據攔截器進行加載當前線程的HttpResponse 和 HttpRequest 對象
 * 在非Controller層獲取Http對象信息
 */
public class RequestResponseContext {
	
	private static ThreadLocal<HttpServletRequest> REQUEST_CHREADLOCAL = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> REPONSE_THREADLOCAL = new ThreadLocal<HttpServletResponse>();
	
	public static void setRquest(HttpServletRequest request){
		REQUEST_CHREADLOCAL.set(request);
	}
	
	public static HttpServletRequest getRequest(){
		return REQUEST_CHREADLOCAL.get();
	}
	
	public static void removeRequest(){
		REQUEST_CHREADLOCAL.remove();
	}
	
	public static void setResponse(HttpServletResponse response){
		REPONSE_THREADLOCAL.set(response);
	}
	
	public static HttpServletResponse getResponse(){
		return REPONSE_THREADLOCAL.get();
	}
	
	public static void removeResponse(){
		REPONSE_THREADLOCAL.remove();
	}
	
}

攔截器,繼承HandlerInterceptorAdapter,在建立以前和結束後,要將對象存入和移除。對象

/**
 * Response和Request攔截器,主要用於獲取Response
 * 經過攔截器保存當前的請求的對象信息進行處理
 */
public class HttpServletResponseInterceptor extends HandlerInterceptorAdapter{

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		RequestResponseContext.removeRequest();
		RequestResponseContext.removeResponse();
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		RequestResponseContext.setRquest(request);
		RequestResponseContext.setResponse(response);
		return true;
	}
}

 

若有其餘方法,望廣大網友告知。繼承

相關文章
相關標籤/搜索