欢迎来到天天文库
浏览记录
ID:41126255
大小:26.00 KB
页数:4页
时间:2019-08-17
《Tomcat源码分析(5)容器处理连接之servlet的映射》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、智慧人大有能力 诚信・正直・创新有知识的人力上加力Tomcat源码分析(五)--容器处理连接之servlet的映射本文所要解决的问题:一个http请求过来,容器是怎么知道选择哪个具体servlet?我们知道,一个Context容器表示一个web应用,一个Wrapper容器表示一个servlet,所以上面的问题可以转换为怎么由Context容器选择servlet,答案是映射器。映射器是实现了Mapper接口的类,作用就是根据请求连接(主要是协议和路径)来选择下一个容器,可以看做是一个哈希表,根据关键字段来选择具体的值
2、,Mapper接口的定义为:[java]publicinterfaceMapper{publicContainergetContainer();//返回与该映射器相关联的容器publicvoidsetContainer(Containercontainer);publicStringgetProtocol();//返回与该映射器处理的协议publicvoidsetProtocol(Stringprotocol);publicContainermap(Requestrequest,booleanupdate);//映射函数
3、,实现该函数}在Tomcat源码分析(四)--容器处理链接之责任链模式中已经知道,请求连接到达StandardContext容器的invoke方法,在StandardContext容器有一句这样的代码:[java]wrapper=(Wrapper)context.map(request,true);这句代码表示容器会调用map方法来映射请求到具体的wrapper上,意思就是说,根据连接请求request来选择wrapper。上面的map会调用父类ContainerBase的map方法来找到具体的映射器,至于这个映射器和容
4、器是怎么关联上的,具体请参考Tomcat源码分析(三)--连接器是如何与容器关联的?这篇文章,大致原理是一样的。StandardContext容器有一个标准的映射器实现类StandardContextMapper,所以最终会调用到映射器StandardContextMapper的map方法,这个方法是选择servlet的关键(省略了一些代码):[java]publicContainermap(Requestrequest,booleanupdate){//Identifythecontext-relativeURItob
5、emappedStringcontextPath=((HttpServletRequest)request.getRequest()).getContextPath();StringrequestURI=((HttpRequest)request).getDecodedRequestURI();StringrelativeURI=requestURI.substring(contextPath.length());//ApplythestandardrequestURImappingrulesfromthespecifi
6、cationWrapperwrapper=null;StringservletPath=relativeURI;StringpathInfo=null;HansonTel:15360452825.Mail:hansonjan@163.com智慧人大有能力 诚信・正直・创新有知识的人力上加力Stringname=null;//Rule1--ExactMatchif(wrapper==null){if(debug>=2)context.log("Tryingexactmatch");if(!(relativeURI.e
7、quals("/")))name=context.findServletMapping(relativeURI);if(name!=null)wrapper=(Wrapper)context.findChild(name);if(wrapper!=null){servletPath=relativeURI;pathInfo=null;}}//Rule2--PrefixMatchif(wrapper==null){if(debug>=2)context.log("Tryingprefixmatch");servletPat
8、h=relativeURI;while(true){name=context.findServletMapping(servletPath+"/*");if(name!=null)wrapper=(Wrapper)context.findChild(name);if(wrapper!=null){pathInfo=r
此文档下载收益归作者所有