如何在服务层直接拿到HttpServletRequest

来源:互联网转载和整理 2024-05-15 14:11:11

httpservlet

大家都知道 能在Controller/action层获取 HttpServletRequest , 但是这里给大家备份的 是 从代码内部 service层获取HttpServletRequest 工具类。 具体如下:

importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;importorg.springframework.web.context.request.RequestContextHolder;importorg.springframework.web.context.request.ServletRequestAttributes;publicclassContextHolderUtils{publicstaticHttpServletRequestgetRequest(){HttpServletRequestrequest=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();returnrequest;}publicstaticHttpSessiongetSession(){HttpSessionsession=getRequest().getSession();returnsession;}}