面试--servlet如何获取session?(51)

来源:互联网 发布:net域名注册 编辑:程序博客网 时间:2024/06/05 19:05

The servlet can get a session object by calling the getSession method of the javax.servlet.http.HttpServletRequest interface. When the getSession method is invoked, the request object must somehow call the manager associated with the context. The manager either creates a new session object or returns the existing one. For the request object to be able to access the manager, it must have access to the context. To achieve this, in the invoke method of the SimpleWrapperValve class, you call the setContext method of the org.apache.catalina.Request interface, passing the Context. Remember that the SimpleWrapperValve calss’s invoke method calls the requested servlet’s service method. The invoke method of the SimpleWrapperValve class is given in following:

    public void invoke(Request request, Response response, ValveContext valveContext)throws IOExveption, ServletException{        SimpleWrapper wrapper = (SimpleWrapper)getContainer();        ServletRequest req = request.getRequest();        ServletResponse sres = response.getResponse();        Servlet servlet = null;        HttpServletRequest hreq = null;        if(sreq instanceof HttpServletRequest)            hreq = (HttpServletRequest)sreq;        HttpServletResponse hres = null;        if(sres instanceof HttpServletResponse)            hres = (HttpServletResponse)sres;        //pass the Context to the Request object so that         //the Request object can call the Manager         Context  context =(Context)wrapper.getParent();         request.setContext(context);         //Allocate a servlet instance to process this request          try{             servlet = wrapper.allocate();             if(hres!=null && hreq!=null){                 servlet.service(hreq,hres);             }else{                 servlet.service(sreq,sres);             }         }catch(ServletException  e){}    }

You have access to the wrapper ,therefore you can obtain the context by calling the getParent method of the Container interface. Note that the wrapper was added to a context. Once you have the context, you can then call the setContext method of the Request interface. Once you have the manager, obtaining a session object or creating a new one is straightforward.

0 0
原创粉丝点击