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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自驱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值