将httpsession的实例传到DAO里面

解决方案 »

  1.   

    一层层传递到DAO中不一定是好的做法,因为这样到处代码都要见到HttpSession对象
    你可以考虑先增加一个Filter过滤所有的请求,类似代码
    public class MyFilter implements Filter{
    public static ThreadLocal session = new ThreadLocal();    public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {
            session.set(((HttpServletRequest)req).getSession());
            chain.doFilter(req, resp);
        }
    }然后你在DAO中直接MyFilter.session.get()就可以取出Session
    ThreadLocal可以保证不会出现线程安全问题
      

  2.   

    我是想,能不能不用传值,直接在DAO中获取到session中的值?
      

  3.   

    HttpSession.getSession()........................
      

  4.   

    。我已经把代码都写出来还不够详细??
    新建一个Filter,就是我上述的代码。在web.xml中配置这个Filter过滤所有的请求,也就是/*
    然后你在任何地方都可以MyFilter.session.get()来得到正确的Session了
      

  5.   

    1.首先创建ThreadSession.java如下
    public class ThreadSession { private static ThreadLocal _session = new ThreadLocal(); public static HttpSession getHttpSession() {
    ThreadLocal threadlocal = _session;
    synchronized (threadlocal) {
    HashMap map = (HashMap) _session.get();
    if (map != null)
    return (HttpSession) map.get("httpSession");
    }
    return null;
    }
    public static void setHttpSession(HttpSession httpSession) {
    synchronized (_session) {
    HashMap map = (HashMap) _session.get();
    if (map == null)
    map = new HashMap();
    map.put("httpSession", httpSession);
    setObject(map);
    }
    }
    }2.在Action入口处
    ThreadSession.setHttpSession(request.getSession());3.在上记Action的出口之前所有地方,比如logic,DAO等都可以直接通过ThreadSession.getHttpSession()得到你保存过的对象.
      

  6.   

    为什么从dao取呢?
    只能用request了,再从request得到session.
      

  7.   

    看来楼主是没有对分层所带的好处充分理解啊,打着分层的幌子干不是分层的事情,还不如回到MODEL1时代简单点
      

  8.   

    用个单实例吧,相当于资源管理器,把session也让这个单实例来管理,这样就可以用静态方法得到session,而不必传值
      

  9.   

    HttpSession session=ServletActionContext.getRequest().getSession();可以直接通过这个得到。