JSF 源代码赏析之Lifecycle

来源:互联网 发布:校园网络诈骗案例 编辑:程序博客网 时间:2024/04/28 16:50

JSF 源代码赏析之Lifecycle

关键字: jsf sourcecode lifecycle

   JSF的生命周期在JSF应用中起着至关重要的作用,每一个JSF请求的处理都需要经过一次生命周期,本文从源码的角度分析JSF的生命周期。
   在讨论生命周期之前,我们先要讨论FacesContext的一些元素,他们在整个生命周期中扮演了非常重要的角色。么个JSF应用必须保存它所处理的请求信息,FacesContext为处理请求和生成响应保存了所有必需的上下文信息,具体而言,它包括:
     1.信息队列,MessageQueue,保存所有的消息
     2.当前的组件树,ViewRoot,
     3.外部上下文,ExternalContext
     4.Application。
  下面就是Sun的FacesContextImpl中的变量:
 
com.sun.faces.context.FacesContextImpl:
  1. // Relationship Instance Variables   
  2.      private ResponseStream responseStream = null;   
  3.      private ResponseWriter responseWriter = null;   
  4.      private ExternalContext externalContext = null;   
  5.      private Application application = null;   
  6.      private UIViewRoot viewRoot = null;   
  7.      private ELContext elContext = null;   
  8.      private RenderKitFactory rkFactory;   
  9.      private RenderKit lastRk;   
  10.      private String lastRkId;   
  11.   
  12.      /**   
  13.       * Store mapping of clientId to ArrayList of FacesMessage   
  14.       * instances.  The null key is used to represent FacesMessage instances   
  15.       * that are not associated with a clientId instance.   
  16.       */   
  17.      private Map<String,List<FacesMessage>> componentMessageLists;   
  18.      // Attribute Instance Variables   
  19.   
  20.      private boolean renderResponse = false;   
  21.      private boolean responseComplete = false;   

这里面有很多重要的对象值得我们去研究,按照从上到下的顺序,我们先来看看ExternalContext。
ExternalContext其实是对ServletContext(或PortletContext)的封装,提供了访问外部容器资源的各种方法,ExternalContext基类定义如下:
javax.faces.context.ExternalContext:
 
  1. public abstract class ExternalContext {  
  2.     
  3.      
  4.     public static final String BASIC_AUTH = "BASIC";  
  5.     public static final String CLIENT_CERT_AUTH = "CLIENT_CERT";  
  6.     public static final String DIGEST_AUTH = "DIGEST";  
  7.     public static final String FORM_AUTH = "FORM";  
  8.   
  9.     // ---------------------------------------------------------- Public Methods  
  10.     public abstract void dispatch(String path)  
  11.     throws IOException;  
  12.     public abstract String encodeActionURL(String url);  
  13.       
  14.     public abstract String encodeNamespace(String name);  
  15.     public abstract String encodeResourceURL(String url);  
  16.     public abstract String getAuthType();  
  17.     public abstract Object getContext();  
  18.     public abstract String getInitParameter(String name);  
  19.     public abstract Map getInitParameterMap();  
  20.     public abstract String getRemoteUser();  
  21.     public abstract Object getRequest();  
  22.     public void setRequest(Object request) {  
  23.         ExternalContext impl;  
  24.         if (null != (impl = (ExternalContext) this.getRequestMap().  
  25.                 get("com.sun.faces.ExternalContextImpl"))) {  
  26.             impl.setRequest(request);  
  27.             return;  
  28.         }  
  29.           
  30.         throw new UnsupportedOperationException();  
  31.     }  
  32.     public void setRequestCharacterEncoding(String encoding) throws UnsupportedEncodingException {  
  33.         ExternalContext impl;  
  34.         if (null != (impl = (ExternalContext) this.getRequestMap().  
  35.                 get("com.sun.faces.ExternalContextImpl"))) {  
  36.             impl.setRequestCharacterEncoding(encoding);  
  37.             return;  
  38.         }  
  39.         throw new UnsupportedOperationException();  
  40.     }  
  41.     public abstract String getRequestContextPath();  
  42.     public abstract Locale getRequestLocale();  
  43.     public abstract Iterator<locale></locale> getRequestLocales();  
  44.     public abstract Iterator<string></string> getRequestParameterNames();  
  45.     public abstract String getRequestPathInfo();  
  46.     public abstract String getRequestServletPath();  
  47.       
  48.     public String getRequestCharacterEncoding() {  
  49.         ExternalContext impl;  
  50.         if (null != (impl = (ExternalContext) this.getRequestMap().  
  51.                 get("com.sun.faces.ExternalContextImpl"))) {  
  52.             //noinspection TailRecursion  
  53.             return impl.getRequestCharacterEncoding();  
  54.         }  
  55.         throw new UnsupportedOperationException();  
  56.     }  
  57.   
  58.     public String getRequestContentType() {  
  59.         ExternalContext impl;  
  60.         if (null != (impl = (ExternalContext) this.getRequestMap().  
  61.                 get("com.sun.faces.ExternalContextImpl"))) {  
  62.             //noinspection TailRecursion  
  63.             return impl.getRequestContentType();  
  64.         }  
  65.   
  66.         throw new UnsupportedOperationException();  
  67.     }  
  68.   
  69.     public String getResponseCharacterEncoding() {  
  70.         ExternalContext impl;  
  71.         if (null != (impl = (ExternalContext) this.getRequestMap().  
  72.                 get("com.sun.faces.ExternalContextImpl"))) {  
  73.             //noinspection TailRecursion  
  74.             return impl.getResponseCharacterEncoding();  
  75.         }  
  76.           throw new UnsupportedOperationException();  
  77.     }  
  78.   
  79.      public String getResponseContentType() {  
  80.         ExternalContext impl;  
  81.         if (null != (impl = (ExternalContext) this.getRequestMap().  
  82.                 get("com.sun.faces.ExternalContextImpl"))) {  
  83.             //noinspection TailRecursion  
  84.             return impl.getResponseContentType();  
  85.         }
  86.         throw new UnsupportedOperationException();  
  87.     }  
  88.     public abstract URL getResource(String path) throws MalformedURLException;  
  89.     public abstract InputStream getResourceAsStream(String path);  
  90.     public abstract Set<string></string> getResourcePaths(String path);  
  91.     public abstract Object getResponse();  
  92.     public abstract Object getSession(boolean create);  
  93.     public abstract Principal getUserPrincipal();  
  94.     public abstract boolean isUserInRole(String role);  
  95.     public abstract void log(String message, Throwable exception);  
  96.     public abstract void redirect(String url) throws IOException;  
  97. }  

这个抽象类共有1000多行,提供了访问外部资源的各种方法,主要是对ServletContext或是PortletContext中方法的封装,比如getRemoteUser、getRequest、getSession等方法都是很常用的,但是在运用时也要注意,如果在程序中写死是ServletContext或HttpServletRequest,那么以后对于更换到Portal环境中是不利的,这个如果需要转换的话需要注意了。
    下面来看看Application对象。Application对象是应用系统范围内的单例类,提供了对FacesContext文件的对象封装,从这个对象中可以得到很多FacesContext文件中的配置,还是来看看定义吧.

  1.  // ------------------------------------------------------------- Properties   
  2.   
  3.  public abstract ActionListener getActionListener();   
  4.   
  5.   
  6.  public abstract void setActionListener(ActionListener listener);   
  7.   
  8.   
  9.  public abstract void setDefaultLocale(Locale locale);   
  10.   
  11.  public abstract String getDefaultRenderKitId();   
  12.   
  13.   
  14.  public abstract void setDefaultRenderKitId(String renderKitId);   
  15.   
  16.  public abstract String getMessageBundle();   
  17.   
  18.   
  19.  public abstract void setMessageBundle(String bundle);   
  20.   
  21.   
  22.  public abstract NavigationHandler getNavigationHandler();   
  23.   
  24.   
  25.  public abstract void setNavigationHandler(NavigationHandler handler);   
  26.   
  27.   
  28.  public abstract PropertyResolver getPropertyResolver();   
  29.   
  30.   
  31.     
  32.  public ResourceBundle getResourceBundle(FacesContext ctx, String name) {   
  33.      Application app = getRIApplicationImpl(ctx);   
  34.      if (app != null) {   
  35.          //noinspection TailRecursion   
  36.          return app.getResourceBundle(ctx, name);   
  37.      }   
  38.         
  39.      throw new UnsupportedOperationException();   
  40.  }   
  41.   
  42.  public abstract VariableResolver getVariableResolver();   
  43.   
  44.   
  45.  public abstract void setVariableResolver(VariableResolver resolver);   
  46.   
  47.   
  48.  public void addELResolver(ELResolver resolver) {   
  49.      Application app = getRIApplicationImpl();   
  50.      if (app != null) {   
  51.          app.addELResolver(resolver);   
  52.      } else {   
  53.          throw new UnsupportedOperationException();   
  54.      }   
  55.  }   
  56.   
  57.  public ELResolver getELResolver() {   
  58.      Application app = getRIApplicationImpl();   
  59.      if (app != null) {   
  60.          //noinspection TailRecursion   
  61.          return app.getELResolver();   
  62.      }   
  63.      throw new UnsupportedOperationException();   
  64.  }   
  65.   
  66.   
  67.  public abstract ViewHandler getViewHandler();   
  68.   
  69.  public abstract void setViewHandler(ViewHandler handler);   
  70.   
  71.  public abstract StateManager getStateManager();   
  72.   
  73.  public abstract void setStateManager(StateManager manager);   
  74.   
  75.   
  76.  // ------------------------------------------------------- Object Factories   
  77.   
  78.  public abstract void addComponent(String componentType,   
  79.                                    String componentClass);   
  80.   
  81.   
  82.  public abstract UIComponent createComponent(String componentType)   
  83.      throws FacesException;   
  84.   
  85.   
  86.  public abstract UIComponent createComponent(ValueBinding componentBinding,   
  87.                                              FacesContext context,   
  88.                                              String componentType)   
  89. rows FacesException;   
  90.   
  91.  public UIComponent createComponent(ValueExpression componentExpression,   
  92.                                     FacesContext context,   
  93.                                     String componentType)   
  94. rows FacesException {   
  95.      if (null == componentExpression || null == context ||   
  96.          null == componentType) {   
  97.         // PENDING - i18n   
  98.          StringBuilder builder = new StringBuilder(64);   
  99.          builder.append("null parameters - ");   
  100.          builder.append("componentExpression: ").append(componentExpression);   
  101.          builder.append(", context: ").append(context);   
  102.          builder.append(", componentType: ").append(componentType);   
  103.          throw new NullPointerException(builder.toString());   
  104.      }   
  105.   
  106.      Object result;   
  107.      boolean createOne = false;   
  108.   
  109.      try {   
  110.          if (null != (result =    
  111.              componentExpression.getValue(context.getELContext()))) {   
  112.              // if the result is not an instance of UIComponent   
  113.              createOne = (!(result instanceof UIComponent));   
  114.              // we have to create one.   
  115.          }   
  116.          if (null == result || createOne) {   
  117.              result = this.createComponent(componentType);   
  118.              componentExpression.setValue((context.getELContext()), result);   
  119.          }   
  120.      } catch (ELException elex) {   
  121.          throw new FacesException(elex);   
  122.      }   
  123.   
  124.      return (UIComponent) result;       
  125.  }   
  126.   
  127.   
  128.  public abstract Iterator<String> getComponentTypes();   
  129.   
  130.   
  131.  public abstract void addConverter(String converterId,    
  132.   
  133.  public abstract void addConverter(Class targetClass,   
  134.                                    String converterClass);   
  135.   
  136.  public abstract Converter createConverter(String converterId);   
  137.   
  138.   
  139.  public abstract Converter createConverter(Class targetClass);   
  140.   
  141.   
  142.  public abstract Iterator<String> getConverterIds();   
  143.   
  144.   
  145.   
  146.  public ExpressionFactory getExpressionFactory() {   
  147.      Application app = getRIApplicationImpl();   
  148.      if (app != null) {   
  149.          //noinspection TailRecursion   
  150.          return app.getExpressionFactory();   
  151.      }   
  152.   
  153.      throw new UnsupportedOperationException();   
  154.  }   
  155.   
  156.   
  157.   
  158.  public Object evaluateExpressionGet(FacesContext context,   
  159.                                      String expression,   
  160.                                      Class expectedType) throws ELException {   
  161.      Application app = getRIApplicationImpl(context);   
  162.      if (app != null) {   
  163.          //noinspection TailRecursion   
  164.          return app.evaluateExpressionGet(context, expression, expectedType);   
  165.      }   
  166.      throw new UnsupportedOperationException();   
  167.  }   
  168.   
  169.  public abstract MethodBinding createMethodBinding(String ref,   
  170.                                                    Class params[])   
  171.      throws ReferenceSyntaxException;   
  172.   
  173.  public abstract Iterator<Locale> getSupportedLocales();   
  174.   
  175.   
  176.  public abstract void setSupportedLocales(Collection<Locale> locales);   
  177.   
  178.   
  179.  public void addELContextListener(ELContextListener listener) {   
  180.      Application app = getRIApplicationImpl();   
  181.      if (app != null) {   
  182.          app.addELContextListener(listener);   
  183.      } else {   
  184.          throw new UnsupportedOperationException();   
  185.      }   
  186.  }   
  187.   
  188.  public void removeELContextListener(ELContextListener listener) {   
  189.      Application app = getRIApplicationImpl();   
  190.      if (app != null) {   
  191.          app.removeELContextListener(listener);   
  192.      } else {   
  193.          throw new UnsupportedOperationException();   
  194.      }   
  195.   
  196.  }   
  197.   
  198.  public ELContextListener [] getELContextListeners() {   
  199.      Application app = getRIApplicationImpl();   
  200.      if (app != null) {   
  201.          //noinspection TailRecursion   
  202.          return app.getELContextListeners();   
  203.      } else {   
  204.          throw new UnsupportedOperationException();   
  205.      }   
  206.  }   
  207.   
  208. public abstract void addValidator(String validatorId,    
  209.           String validatorClass);   
  210.   
  211. public abstract Validator createValidator(String validatorId)   
  212.      throws FacesException;   
  213.   
  214. public abstract Iterator<String> getValidatorIds();   
  215. public abstract ValueBinding createValueBinding(String ref)   
  216.      throws ReferenceSyntaxException;   
  217.   
  218.   
  219.  // --------------------------------------------------------- Private Methods   
  220.   
  221.   
  222.  private static Application getRIApplicationImpl(FacesContext context) {   
  223.      ExternalContext extContext;   
  224.      if (context != null) {   
  225.          extContext = context.getExternalContext();   
  226.      } else {   
  227.          extContext =   
  228.               FacesContext.getCurrentInstance().getExternalContext();   
  229.      }   
  230.      if (extContext != null) {   
  231.          return ((Application) extContext.getApplicationMap().   
  232.               get("com.sun.faces.ApplicationImpl"));   
  233.      }   
  234.      return null;   
  235.  }   
  236.   
  237.  private static Application getRIApplicationImpl() {   
  238.      return getRIApplicationImpl(null);   
  239.  }