Advertisement
Guest User

Untitled

a guest
Jul 20th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. public class CurrentConnectionInfo implements Filter {
  2.  
  3. private static final ThreadLocal<HttpServletRequest> currentRequest = new ThreadLocal<HttpServletRequest>();
  4. private static final ThreadLocal<HttpServletResponse> currentResponse = new ThreadLocal<HttpServletResponse>();
  5.  
  6. public static HttpServletRequest getCurrentRequest() {
  7. if (currentRequest.get() == null) {
  8. throw new RuntimeException("not in connection handle cycle");
  9. }
  10. return currentRequest.get();
  11. }
  12.  
  13. public static HttpServletResponse getCurrentResponse() {
  14. if (currentResponse.get() == null) {
  15. throw new RuntimeException("not in connection handle cycle");
  16. }
  17. return currentResponse.get();
  18. }
  19.  
  20. public static HttpSession getSession() {
  21. return getCurrentRequest().getSession();
  22. }
  23.  
  24. public static boolean hasConnection() {
  25. return currentRequest.get() != null;
  26. }
  27.  
  28. @Override
  29. public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain next)
  30. throws IOException, ServletException {
  31. try {
  32. if (rq instanceof HttpServletRequest)
  33. currentRequest.set((HttpServletRequest) rq);
  34. if (rs instanceof HttpServletResponse)
  35. currentResponse.set((HttpServletResponse) rs);
  36. next.doFilter(rq, rs);
  37. } finally {
  38. currentResponse.set(null);
  39. currentRequest.set(null);
  40. }
  41. }
  42.  
  43. @Override
  44. public void init(FilterConfig arg0) throws ServletException {
  45.  
  46. }
  47.  
  48. @Override
  49. public void destroy() {
  50.  
  51. }
  52.  
  53. }
  54.  
  55.  
  56. <filter>
  57. <filter-name>currentConnectionFilter</filter-name>
  58. <filter-class>foo.bar.CurrentConnectionInfo</filter-class>
  59. </filter>
  60.  
  61. <filter-mapping>
  62. <filter-name>currentConnectionFilter</filter-name>
  63. <url-pattern>/*</url-pattern>
  64. </filter-mapping>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement