Get HttpSession | Request from a simple Java non-servlet class

I want the session Object not to be in the servlet class, but normal from our application.

web.xml

<listener>
        <listener-class>com.abc.web.ApplicationManager</listener-class>
</listener>
<listener>
        <listener-class>com.abc.web.SessionManager</listener-class>
</listener>

ViewPrices.java

public class ViewPrices implements Cloneable, Serializable {

 Session session = request.getSession();
                   servletContext.getSession()
                   anyWay.getSession();
}
+5
source share
3 answers

I do not think it is possible for direct access to the session and the request of the object. What you can do is pass the session and / or request the object from the servlet to the Java class, either in some method or in the constructor of the Java class.

+1
source

call it:

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 register it in the 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>
+15
source

, .. . - . . :

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

, , - , -:

  • ThreadLocal Filter ( )
  • - ( ), .
+7

All Articles