Java service層獲取HttpServletRequest的工具類

執筆記憶的空白發表於2018-10-09

大家都知道 能在Controller/action層獲取 HttpServletRequest , 但是這裡給大家備份的 是 從程式碼內部  service層獲取HttpServletRequest 工具類。  具體如下:

package com.base.common.sessionutils;

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

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

public class ContextHolderUtils {

	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;

	}

	public static HttpSession getSession() {
		HttpSession session = getRequest().getSession();
		return session;
	}

}

 

這樣其他服務層使用的時候,ContextHolderUtils.getRequest();  即可

 

 

 

相關文章