首先,在web.xml配置:java
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
而後,就能夠在service或者dao中獲取HttpServletRequest 的代碼以下:web
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest();
爲了方便,能夠如上代碼提取到一個工具方法中,避免重複。例如:原本需求是要獲取session中存的國際化信息Locale,就能夠這樣處理:spring
/** * 獲取當前Session中Locale信息 * @author weijuer * @return */ public static Locale getLocale() { // 獲取HttpServletRequest HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return (Locale) request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME); }
我用Spring MVC , 在Controller方法裏每次都要寫一個HttpServletRequest request參數,Spring纔會注入request,而後我就產生了一個神奇的想法,寫一個BaseController把request注入,而後其它Controller繼承後就不須要再寫request就能夠直接使用父類的request: session
abstract class BaseController { private HttpServletRequest request; public HttpServletRequest getRequest() { return request; } @Resource public void setRequest(HttpServletRequest request) { this.request = request; } }
事實上這麼也成功注入了,子Controller能夠使用request。工具