从简单的java类获取HttpSession | Request而不是servlet类

时间:2011-05-03 08:01:47

标签: java jsp servlets java-ee

我希望会话对象不在servlet类中,而是普通的应用程序。

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();
}

3 个答案:

答案 0 :(得分:16)

打电话给:

RequestFilter.getSession();
RequestFilter.getRequest();
自定义过滤器上的

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() {
    }
}

您将其注册到您的web.xml文件中:

<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>

答案 1 :(得分:7)

有多种方法可以做到这一点,但是......不这样做。只有您的Web图层才能访问该会话。其他层应该只从它需要的会话中获取参数。例如:

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

您必须获取请求的选项,以及仍在Web层中的非servlet类中的会话:

  • 将请求存储在ThreadLocal的{​​{1}}中(之后清理)
  • 将其作为参数传递 - 在构造函数中(如果对象在每个请求上实例化)或作为方法参数传递。

答案 2 :(得分:1)

我认为不可能直接访问会话和请求对象。你可以做的是在某个方法或Java类的构造函数中将会话和/或请求对象从servlet传递给Java类。