`
glacier3
  • 浏览: 376903 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

对petsore的ControllerServlet类的分析

阅读更多

     最近看看了PETSTORE2.0的一些代码,发现有很多东西值得学习。

      下面我来分析一下ControllerServlet这个SERVLET,它位于com.sun.javaee.blueprints.petstore.controller包之中。它的作用是根据请求的SERVLET的URi完成不同的特定功能,我只看了产生随机图片的那个调用。

代码如下:

  1.    
  2. /**  
  3.  * This servlet is responsible for interacting with a client  
  4.  * based controller and will fetch resources including content  
  5.  * and relevant script.  
  6.  *  
  7.  * This servlet also will process requests for client ob
  8. servers  
  9.  */  
  10. public class ControllerServlet extends HttpServlet {   
  11.        
  12.     private static final boolean bDebug=false;   
  13.     private HashMap<String, ControllerAction> actionMap = new HashMap<String, ControllerAction>();   
  14.        
  15.     @Override    
  16.     public void init(ServletConfig config) throws ServletException {   
  17.         super.init(config);   
  18.         ServletContext context = config.getServletContext();   
  19.         CatalogFacade cf = (CatalogFacade) context.getAttribute("CatalogFacade");   
  20.         actionMap.put("/ImageServlet"new ImageAction(context));   
  21.         actionMap.put("/controller"new DefaultControllerAction(context));   
  22.         actionMap.put("/faces/CaptchaServlet"new CaptchaAction());   
  23.         actionMap.put("/TagServlet"new TagXmlAction(cf));   
  24.         actionMap.put("/catalog"new CatalogXmlAction(cf));   
  25.     }   
  26.        
  27.     public ControllerAction findAction(String servletPath) {   
  28.         return actionMap.get(servletPath);   
  29.     }   
  30.     @Override    
  31.     public void destroy() {   
  32.         actionMap = null;   
  33.     }   
  34.        
  35.     @Override    
  36.     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
  37.         String servletPath = request.getServletPath();   
  38.         if(bDebug) System.out.println(" ServletPath: " + servletPath + ", pathinfo: " + request.getPathInfo());   
  39.         ControllerAction action = actionMap.get(servletPath);   
  40.         if (action != null) {   
  41.             if(bDebug) System.out.println(" Found action " + action.getClass().getName());   
  42.             action.service(request, response);   
  43.         } else {   
  44.             PetstoreUtil.getLogger().log(Level.SEVERE, "Servlet '" + request.getServletPath() + "' not registered in ControllerServlet!!");   
  45.             HttpServletResponse httpResponse=(HttpServletResponse)response;   
  46.             httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);   
  47.         }   
  48.     }   
  49. }   

它的运作流程可以很容易的看出来:首先SERVLET加载入所有需要处理的servlet URI,把他们都存入一个HASHmAP当中,然后在DOGET中,读取请求的SERVLET的RUI,得到特定的URI后就进行相应的操作。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics