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