最近看看了PETSTORE2.0的一些代码,发现有很多东西值得学习。
下面我来分析一下ControllerServlet这个SERVLET,它位于com.sun.javaee.blueprints.petstore.controller包之中。它的作用是根据请求的SERVLET的URi完成不同的特定功能,我只看了产生随机图片的那个调用。
代码如下:
- /**
- * This servlet is responsible for interacting with a client
- * based controller and will fetch resources including content
- * and relevant script.
- *
- * This servlet also will process requests for client ob
- servers
- */
- public class ControllerServlet extends HttpServlet {
- private static final boolean bDebug=false;
- private HashMap<String, ControllerAction> actionMap = new HashMap<String, ControllerAction>();
- @Override
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- ServletContext context = config.getServletContext();
- CatalogFacade cf = (CatalogFacade) context.getAttribute("CatalogFacade");
- actionMap.put("/ImageServlet", new ImageAction(context));
- actionMap.put("/controller", new DefaultControllerAction(context));
- actionMap.put("/faces/CaptchaServlet", new CaptchaAction());
- actionMap.put("/TagServlet", new TagXmlAction(cf));
- actionMap.put("/catalog", new CatalogXmlAction(cf));
- }
- public ControllerAction findAction(String servletPath) {
- return actionMap.get(servletPath);
- }
- @Override
- public void destroy() {
- actionMap = null;
- }
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String servletPath = request.getServletPath();
- if(bDebug) System.out.println(" ServletPath: " + servletPath + ", pathinfo: " + request.getPathInfo());
- ControllerAction action = actionMap.get(servletPath);
- if (action != null) {
- if(bDebug) System.out.println(" Found action " + action.getClass().getName());
- action.service(request, response);
- } else {
- PetstoreUtil.getLogger().log(Level.SEVERE, "Servlet '" + request.getServletPath() + "' not registered in ControllerServlet!!");
- HttpServletResponse httpResponse=(HttpServletResponse)response;
- httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
- }
- }
- }
它的运作流程可以很容易的看出来:首先SERVLET加载入所有需要处理的servlet URI,把他们都存入一个HASHmAP当中,然后在DOGET中,读取请求的SERVLET的RUI,得到特定的URI后就进行相应的操作。