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