Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CurrentConnectionInfo implements Filter {
- private static final ThreadLocal<HttpServletRequest> currentRequest = new ThreadLocal<HttpServletRequest>();
- private static final ThreadLocal<HttpServletResponse> currentResponse = new ThreadLocal<HttpServletResponse>();
- public static HttpServletRequest getCurrentRequest() {
- if (currentRequest.get() == null) {
- throw new RuntimeException("not in connection handle cycle");
- }
- return currentRequest.get();
- }
- public static HttpServletResponse getCurrentResponse() {
- if (currentResponse.get() == null) {
- throw new RuntimeException("not in connection handle cycle");
- }
- return currentResponse.get();
- }
- public static HttpSession getSession() {
- return getCurrentRequest().getSession();
- }
- public static boolean hasConnection() {
- return currentRequest.get() != null;
- }
- @Override
- public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain next)
- throws IOException, ServletException {
- try {
- if (rq instanceof HttpServletRequest)
- currentRequest.set((HttpServletRequest) rq);
- if (rs instanceof HttpServletResponse)
- currentResponse.set((HttpServletResponse) rs);
- next.doFilter(rq, rs);
- } finally {
- currentResponse.set(null);
- currentRequest.set(null);
- }
- }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- }
- @Override
- public void destroy() {
- }
- }
- <filter>
- <filter-name>currentConnectionFilter</filter-name>
- <filter-class>foo.bar.CurrentConnectionInfo</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>currentConnectionFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement