get HttpSession|Request from simple java class not servlet class

前端 未结 3 401
醉梦人生
醉梦人生 2020-12-03 19:23

i want session Object not in servlet class but ordinary from we application.

WEB.XML


                 


        
相关标签:
3条回答
  • 2020-12-03 19:48

    I don't think it's possible, to directly access session and request object. What you can do is pass the session and/or request object from servlet to a Java class either in some method or in constructor of the Java class.

    0 讨论(0)
  • 2020-12-03 19:48

    There are multiple ways to do that, but.. don't. Only your web layer should have access to the session. The other layers should only get the parameters from the session that it needs. For example:

    service.doSomeBusinessLogic(
         session.getAttribute("currentUser"), 
         session.getAttribute("foo"));
    

    The options that you have to obtain the request, and from it - the session in a non-servlet class, that is still in the web layer:

    • store the request in a ThreadLocal in a Filter (and clean it afterwards)
    • pass it as argument - either in constructor (if the object is instantiated on each request) or as method argument.
    0 讨论(0)
  • 2020-12-03 19:55

    call this:

    RequestFilter.getSession();
    RequestFilter.getRequest();
    

    on your custom filter:

    public class RequestFilter implements Filter {
    
        private static ThreadLocal<HttpServletRequest> localRequest = new ThreadLocal<HttpServletRequest>();
    
    
        public static HttpServletRequest getRequest() {
            return localRequest.get();
        }
    
        public static HttpSession getSession() {
            HttpServletRequest request = localRequest.get();
            return (request != null) ? request.getSession() : null;
        }
    
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            if (servletRequest instanceof HttpServletRequest) {
                localRequest.set((HttpServletRequest) servletRequest);
            }
    
            try {
                filterChain.doFilter(servletRequest, servletResponse);
            } finally {
                localRequest.remove();
            }
        }
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        @Override
        public void destroy() {
        }
    }
    

    that you'll register it into your web.xml file:

    <filter>
        <filter-name>RequestFilter</filter-name>
        <filter-class>your.package.RequestFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>RequestFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    0 讨论(0)
提交回复
热议问题