Java service层获取HttpServletRequest工具类的方法

x33g5p2x  于2022-02-15 转载在 Java  
字(0.7k)|赞(0)|评价(0)|浏览(334)

大家都知道 能在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(); 即可

相关文章