Struts2源码分析

Struts2架构流程图

Struts2部分类介绍

这部分从Struts2参考文档中翻译就可以了。
ActionMapper
        ActionMapper其实是HttpServletRequest和Action调用请求的一个映射,它屏蔽了Action对于Request等Java Servlet类的依赖。Struts2中它的默认实现类是DefaultActionMapper,ActionMapper很大的用处可以根据自己的需要来设计url格式,它自己也有Restful的实现,具体可以参考文档的docs\actionmapper.html。
ActionProxy&ActionInvocation
        Action的一个代理,由ActionProxyFactory创建,它本身不包括Action实例,默认实现DefaultActionProxy是由ActionInvocation持有Action实例。ActionProxy作用是如何取得Action,无论是本地还是远程。而ActionInvocation的作用是如何执行Action,拦截器的功能就是在ActionInvocation中实现的。
ConfigurationProvider&Configuration
        ConfigurationProvider就是Struts2中配置文件的解析器,Struts2中的配置文件主要是尤其实现类XmlConfigurationProvider及其子类StrutsXmlConfigurationProvider来解析


Struts2请求流程
1、客户端发送请求
2、请求先通过ActionContextCleanUp-->FilterDispatcher
3、FilterDispatcher通过ActionMapper来决定这个Request需要调用哪个Action
4、如果ActionMapper决定调用某个Action,FilterDispatcher把请求的处理交给ActionProxy,这儿已经转到它的Delegate--Dispatcher来执行
5、ActionProxy根据ActionMapping和ConfigurationManager找到需要调用的Action类
6、ActionProxy创建一个ActionInvocation的实例
7、ActionInvocation调用真正的Action,当然这涉及到相关拦截器的调用
8、Action执行完毕,ActionInvocation创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。添加PreResultListener可以在Interceptor中实现,不知道其它还有什么方式?


Struts2(2.3.4)部分代码阅读

web.xml配置:

自从struts 2.1.3以后,FilterDispatcher已标注为过时改用StrutsPrepareAndExecuteFilter。我们此文将剖析StrutsPrepareAndExecuteFilter,其在工程中作为一个Filter配置在web.xml中,配置如下:

  1. <filter>  
  2.     <filter-name>struts2</filter-name>  
  3.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  4. </filter>  
  5.   
  6. <filter-mapping>  
  7.     <filter-name>struts2</filter-name>  
  8.     <url-pattern>/*</url-pattern>  
  9. </filter-mapping>  

从org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter开始

  1.  public void init(FilterConfig filterConfig) throws ServletException {  
  2.     //创建一个InitOperations初始化操作的对象  
  3.      InitOperations init = new InitOperations();  
  4.      try {  
  5.          //封装filterConfig,其中有个主要方法getInitParameterNames将参数名字以String格式存储在List中  
  6.          FilterHostConfig config = new FilterHostConfig(filterConfig);  
  7.          // 初始化struts内部日志    
  8.          init.initLogging(config);  
  9.          //创建dispatcher对象,并读取配置文件     
  10.          Dispatcher dispatcher = init.initDispatcher(config);  
  11.          init.initStaticContentLoader(config, dispatcher);  
  12.            
  13.          //初始化类属性:prepare 、execute    
  14.          prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);  
  15.          execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);  
  16. this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);  
  17.   
  18. //回调空的postInit方法  
  19.          postInit(dispatcher, filterConfig);  
  20.      } finally {  
  21.          init.cleanup();  
  22.      }  
  23.  }  

首先看下FilterHostConfig ,只有短短的几行代码,getInitParameterNames是这个类的核心,将Filter初始化参数名称有枚举类型转为Iterator。此类的主要作为是对filterConfig 封装,源码如下: 

  1. public class FilterHostConfig implements HostConfig {  
  2.   
  3.     private FilterConfig config;  
  4.     /* 
  5.      * 构造函数 
  6.      */   
  7.     public FilterHostConfig(FilterConfig config) {  
  8.         this.config = config;  
  9.     }  
  10.       
  11.     //根据init-param配置的param-name获取param-value的值  
  12.     public String getInitParameter(String key) {  
  13.         return config.getInitParameter(key);  
  14.     }  
  15.   
  16.     //返回初始化参数名的List  
  17.     public Iterator<String> getInitParameterNames() {  
  18.         return MakeIterator.convert(config.getInitParameterNames());  
  19.     }  
  20.   
  21.     public ServletContext getServletContext() {  
  22.         return config.getServletContext();  
  23.     }  
  24. }  

InitOperations的initDispatcher方法。initDispatcher方法,创建dispatcher对象,并读取配置文件 。

  1. public Dispatcher initDispatcher(HostConfig filterConfig) {  
  2.     // 创建dispatcher对象,将参数传递dispatcher全局变量  
  3.     Dispatcher dispatcher = createDispatcher(filterConfig);  
  4.     // 初始化配置文件/读取配置文件  
  5.     dispatcher.init();  
  6.     return dispatcher;  
  7. }  

InitOperations的createDispatcher方法。创建Dispatcher,会读取 filterConfig中的配置信息。

  1.     /* 
  2.      * 创建Dispatcher,会读取 filterConfig 
  3.      * 中的配置信息,将配置信息解析出来,封装成为一个Map,然后根绝servlet上下文和参数Map构造Dispatcher 
  4.      */  
  5.     private Dispatcher createDispatcher(HostConfig filterConfig) {  
  6.         Map<String, String> params = new HashMap<String, String>();  
  7.         // 获得在web.xml中所有的配置文件,将参数放入params Map集合中  
  8.         for (Iterator e = filterConfig.getInitParameterNames(); e.hasNext();) {  
  9.             String name = (String) e.next();  
  10.             String value = filterConfig.getInitParameter(name);  
  11.             params.put(name, value);  
  12.         }  
  13.         // 创建Dispatcher 对象,将ServletContext(),将参数赋给Dispatcher的全局私有变量中  
  14.         return new Dispatcher(filterConfig.getServletContext(), params);  
  15.     }  

顺着流程我们看Disptcher的init方法。init方法里就是初始读取一些配置文件等,先看init_DefaultProperties,主要是读取properties配置文件。

  1.         public void init() {  
  2.         /* 
  3.          * 如果 configurationManager为空,则创建configurationManager对象, 
  4.          * 在configurationManager构函数 将 BeanSelectionProvider.DEFAULT_BEAN_NAME(常量值struts) 
  5.          * 赋给全局变量protected String defaultFrameworkBeanName; 
  6.          */  
  7.         if (configurationManager == null) {  
  8.             configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);  
  9.         }  
  10.   
  11.         try {  
  12.             //主要是读取properties配置文件  
  13.             init_DefaultProperties(); // [1]  
  14.             //读取struts-default.xml和Struts.xml的方法  
  15.             init_TraditionalXmlConfigurations(); // [2]  
  16.             init_LegacyStrutsProperties(); // [3]  
  17.             /*  
  18.              * init_CustomConfigurationProviders方式初始自定义的Provider, 
  19.              * 配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。 
  20.              */  
  21.             init_CustomConfigurationProviders(); // [5]  
  22.   
  23.             //Filter的初始化参数  
  24.             init_FilterInitParameters() ; // [6]  
  25.             init_AliasStandardObjects() ; // [7]  
  26.   
  27.             Container container = init_PreloadConfiguration();  
  28.             container.inject(this);  
  29.             init_CheckConfigurationReloading(container);  
  30.             init_CheckWebLogicWorkaround(container);  
  31.   
  32.             if (!dispatcherListeners.isEmpty()) {  
  33.                 for (DispatcherListener l : dispatcherListeners) {  
  34.                     l.dispatcherInitialized(this);  
  35.                 }  
  36.             }  
  37.         } catch (Exception ex) {  
  38.             if (LOG.isErrorEnabled())  
  39.                 LOG.error("Dispatcher initialization failed", ex);  
  40.             throw new StrutsException(ex);  
  41.         }  
  42.     }  

init_DefaultProperties方法,初始化default.properties,具体的初始化操作在DefaultPropertiesProvider类中

  1.     private void init_DefaultProperties() {  
  2.         configurationManager.addContainerProvider(new DefaultPropertiesProvider());  
  3.     }  

打开DefaultPropertiesProvider类源码:

  1.     public void register(ContainerBuilder builder, LocatableProperties props)  
  2.             throws ConfigurationException {  
  3.   
  4.         Settings defaultSettings = null;  
  5.         try {  
  6.             // 读取properties属性文件方法  
  7.             defaultSettings = new PropertiesSettings(  
  8.                     "org/apache/struts2/default");  
  9.         } catch (Exception e) {  
  10.             throw new ConfigurationException(  
  11.                     "Could not find or error in org/apache/struts2/default.properties",  
  12.                     e);  
  13.         }  
  14.   
  15.         loadSettings(props, defaultSettings);  
  16.     }  

再来看init_TraditionalXmlConfigurations方法,这个是读取struts-default.xml和Struts.xml的方法。

  1.     //init_TraditionalXmlConfigurations方法,这个是读取struts-default.xml和Struts.xml的方法  
  2.     private void init_TraditionalXmlConfigurations() {  
  3.         /* 
  4.          * 首先读取web.xml中的config初始参数值 
  5.          * 如果没有配置就使用默认的"struts-default.xml,struts-plugin.xml,struts.xml", 
  6.          * 这儿就可以看出为什么默认的配置文件必须取名为这三个名称了 
  7.          * 如果不想使用默认的名称,直接在web.xml中配置config初始参数即可 
  8.          */  
  9.         String configPaths = initParams.get("config");  
  10.         if (configPaths == null) {  
  11.             configPaths = DEFAULT_CONFIGURATION_PATHS;  
  12.         }  
  13.         String[] files = configPaths.split("\\s*[,]\\s*");  
  14.         for (String file : files) {  
  15.             if (file.endsWith(".xml")) {  
  16.                 //依次解析配置文件,xwork.xml单独解析,除xwork.xml外,  
  17.                 //全都调用createStrutsXmlConfigurationProvider()方法,  
  18.                 //StrutsXmlConfigurationProvider进行解析  
  19.                 if ("xwork.xml".equals(file)) {  
  20.                     configurationManager.addContainerProvider(createXmlConfigurationProvider(file, false));  
  21.                 } else {  
  22.                     configurationManager.addContainerProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));  
  23.                 }  
  24.             } else {  
  25.                 throw new IllegalArgumentException("Invalid configuration file name");  
  26.             }  
  27.         }  
  28.     }   

       StrutsXmlConfigurationProvider类继承XmlConfigurationProvider,而XmlConfigurationProvider又实现 ConfigurationProvider接口。类XmlConfigurationProvider负责配置文件的读取和解析,addAction()方法负责读取<action>标签,并将数据保存在ActionConfig 中;addResultTypes()方法负责将<result-type>标签转化为ResultTypeConfig对象;loadInterceptors()方法负责将<interceptor>标签转化为InterceptorConfi对象;loadInterceptorStack()方法负责将<interceptor-ref>标签转化为 InterceptorStackConfig对象;loadInterceptorStacks()方法负责将<interceptor- stack>标签转化成InterceptorStackConfig对象。而上面的方法最终会被addPackage()方法调用,将所读取到的数据汇集到PackageConfig对象中。

  1.      protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {  
  2.         PackageConfig.Builder newPackage = buildPackageContext(packageElement);  
  3.   
  4.         if (newPackage.isNeedsRefresh()) {  
  5.             return newPackage.build();  
  6.         }  
  7.   
  8.         if (LOG.isDebugEnabled()) {  
  9.             LOG.debug("Loaded " + newPackage);  
  10.         }  
  11.   
  12.         // add result types (and default result) to this package  
  13.         addResultTypes(newPackage, packageElement);  
  14.   
  15.         // load the interceptors and interceptor stacks for this package  
  16.         loadInterceptors(newPackage, packageElement);  
  17.   
  18.         // load the default interceptor reference for this package  
  19.         loadDefaultInterceptorRef(newPackage, packageElement);  
  20.   
  21.         // load the default class ref for this package  
  22.         loadDefaultClassRef(newPackage, packageElement);  
  23.   
  24.         // load the global result list for this package  
  25.         loadGlobalResults(newPackage, packageElement);  
  26.   
  27.         // load the global exception handler list for this package  
  28.         loadGobalExceptionMappings(newPackage, packageElement);  
  29.   
  30.         // get actions  
  31.         NodeList actionList = packageElement.getElementsByTagName("action");  
  32.   
  33.         for (int i = 0; i < actionList.getLength(); i++) {  
  34.             Element actionElement = (Element) actionList.item(i);  
  35.             addAction(actionElement, newPackage);  
  36.         }  
  37.   
  38.         // load the default action reference for this package  
  39.         loadDefaultActionRef(newPackage, packageElement);  
  40.   
  41.         PackageConfig cfg = newPackage.build();  
  42.         configuration.addPackageConfig(cfg.getName(), cfg);  
  43.         return cfg;  
  44.     }  
  45.   
  46.     private List<Document> loadConfigurationFiles(String fileName, Element includeElement) {  
  47.         List<Document> docs = new ArrayList<Document>();  
  48.         List<Document> finalDocs = new ArrayList<Document>();  
  49.         if (!includedFileNames.contains(fileName)) {  
  50.             if (LOG.isDebugEnabled()) {  
  51.                 LOG.debug("Loading action configurations from: " + fileName);  
  52.             }  
  53.   
  54.             includedFileNames.add(fileName);  
  55.   
  56.             Iterator<URL> urls = null;  
  57.             InputStream is = null;  
  58.   
  59.             IOException ioException = null;  
  60.             try {  
  61.                 urls = getConfigurationUrls(fileName);  
  62.             } catch (IOException ex) {  
  63.                 ioException = ex;  
  64.             }  
  65.   
  66.             if (urls == null || !urls.hasNext()) {  
  67.                 if (errorIfMissing) {  
  68.                     throw new ConfigurationException("Could not open files of the name " + fileName, ioException);  
  69.                 } else {  
  70.                     if (LOG.isInfoEnabled()) {  
  71.                     LOG.info("Unable to locate configuration files of the name "  
  72.                             + fileName + ", skipping");  
  73.                     }  
  74.                     return docs;  
  75.                 }  
  76.             }  
  77.   
  78.             URL url = null;  
  79.             while (urls.hasNext()) {  
  80.                 try {  
  81.                     url = urls.next();  
  82.                     is = fileManager.loadFile(url);  
  83.   
  84.                     InputSource in = new InputSource(is);  
  85.   
  86.                     in.setSystemId(url.toString());  
  87.   
  88.                     docs.add(DomHelper.parse(in, dtdMappings));  
  89.                 } catch (XWorkException e) {  
  90.                     if (includeElement != null) {  
  91.                         throw new ConfigurationException("Unable to load " + url, e, includeElement);  
  92.                     } else {  
  93.                         throw new ConfigurationException("Unable to load " + url, e);  
  94.                     }  
  95.                 } catch (Exception e) {  
  96.                     final String s = "Caught exception while loading file " + fileName;  
  97.                     throw new ConfigurationException(s, e, includeElement);  
  98.                 } finally {  
  99.                     if (is != null) {  
  100.                         try {  
  101.                             is.close();  
  102.                         } catch (IOException e) {  
  103.                             LOG.error("Unable to close input stream", e);  
  104.                         }  
  105.                     }  
  106.                 }  
  107.             }  
  108.   
  109.             //sort the documents, according to the "order" attribute  
  110.             Collections.sort(docs, new Comparator<Document>() {  
  111.                 public int compare(Document doc1, Document doc2) {  
  112.                     return XmlHelper.getLoadOrder(doc1).compareTo(XmlHelper.getLoadOrder(doc2));  
  113.                 }  
  114.             });  
  115.   
  116.             for (Document doc : docs) {  
  117.                 Element rootElement = doc.getDocumentElement();  
  118.                 NodeList children = rootElement.getChildNodes();  
  119.                 int childSize = children.getLength();  
  120.   
  121.                 for (int i = 0; i < childSize; i++) {  
  122.                     Node childNode = children.item(i);  
  123.   
  124.                     if (childNode instanceof Element) {  
  125.                         Element child = (Element) childNode;  
  126.   
  127.                         final String nodeName = child.getNodeName();  
  128.                         //解析每个action配置是,对于include文件可以使用通配符*来进行配置  
  129.                         //如Struts.xml中可配置成<include file="actions_*.xml"/>  
  130.                         if ("include".equals(nodeName)) {  
  131.                             //获得file属性 例如: <include file="example.xml"/>  
  132.                             String includeFileName = child.getAttribute("file");  
  133.                             if (includeFileName.indexOf('*') != -1) {  
  134.                                 // handleWildCardIncludes(includeFileName, docs, child);  
  135.                                 ClassPathFinder wildcardFinder = new ClassPathFinder();  
  136.                                 wildcardFinder.setPattern(includeFileName);  
  137.                                   
  138.                                 Vector<String> wildcardMatches = wildcardFinder.findMatches();  
  139.                                 for (String match : wildcardMatches) {  
  140.                                     finalDocs.addAll(loadConfigurationFiles(match, child));  
  141.                                 }   
  142.                             } else {  
  143.                                 finalDocs.addAll(loadConfigurationFiles(includeFileName, child));  
  144.                             }  
  145.                         }  
  146.                     }  
  147.                 }  
  148.                 finalDocs.add(doc);  
  149.                 loadedFileUrls.add(url.toString());  
  150.             }  
  151.   
  152.             if (LOG.isDebugEnabled()) {  
  153.                 LOG.debug("Loaded action configuration from: " + fileName);  
  154.             }  
  155.         }  
  156.         return finalDocs;  
  157.     }  

init_CustomConfigurationProviders方式初始自定义的Provider,配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。

  1.     //init_CustomConfigurationProviders方式初始自定义的Provider,配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。  
  2.     private void init_CustomConfigurationProviders() {  
  3.         /* 
  4.          * 首先读取web.xml中的configProviders初始参数值 
  5.          * 如果有配置则去加载。 
  6.          */  
  7.         String configProvs = initParams.get("configProviders");  
  8.         if (configProvs != null) {  
  9.             String[] classes = configProvs.split("\\s*[,]\\s*");  
  10.             for (String cname : classes) {  
  11.                 try {  
  12.                     Class cls = ClassLoaderUtil.loadClass(cname, this.getClass());  
  13.                     ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();  
  14.                     configurationManager.addContainerProvider(prov);  
  15.                 } catch (InstantiationException e) {  
  16.                     throw new ConfigurationException("Unable to instantiate provider: "+cname, e);  
  17.                 } catch (IllegalAccessException e) {  
  18.                     throw new ConfigurationException("Unable to access provider: "+cname, e);  
  19.                 } catch (ClassNotFoundException e) {  
  20.                     throw new ConfigurationException("Unable to locate provider class: "+cname, e);  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  

现在再回到FilterDispatcher,每次发送一个Request,FilterDispatcher都会调用doFilter方法。doFilter是过滤器的执行方法,它拦截提交的HttpServletRequest请求,HttpServletResponse响应,是strtus2的核心拦截器。

  1.     //每次发送一个Request,StrutsPrepareAndExecuteFilter都会调用doFilter方法  
  2.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  3.   
  4.         HttpServletRequest request = (HttpServletRequest) req;  
  5.         HttpServletResponse response = (HttpServletResponse) res;  
  6.   
  7.         try {  
  8.             //设置编码和国际化    
  9.             prepare.setEncodingAndLocale(request, response);  
  10.             //ActionContext创建  
  11.             prepare.createActionContext(request, response);  
  12.             prepare.assignDispatcherToThread();  
  13.             if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {  
  14.                 chain.doFilter(request, response);  
  15.             } else {  
  16.                 request = prepare.wrapRequest(request);  
  17.                 ActionMapping mapping = prepare.findActionMapping(request, response, true);  
  18.                 //如果找不到对应的action配置  
  19.                 if (mapping == null) {  
  20.                     /* 
  21.                      * 就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中, 
  22.                      * 当然.class文件除外。如果再没有则跳转到404 
  23.                      */  
  24.                     boolean handled = execute.executeStaticResourceRequest(request, response);  
  25.                     if (!handled) {  
  26.                         chain.doFilter(request, response);  
  27.                     }  
  28.                 } else {  
  29.                     /* 
  30.                      * 找到对应action配置文件后,调用ExecuteOperations类中executeAction, 
  31.                      * 开始谳用Action的方法。 
  32.                      */  
  33.                     execute.executeAction(request, response, mapping);  
  34.                 }  
  35.             }  
  36.         } finally {  
  37.             prepare.cleanupRequest(request);  
  38.         }  
  39.     }  
setEncodingAndLocale调用了dispatcher方法的prepare方法。

  1.      //setEncodingAndLocale调用了dispatcher方法的prepare方法  
  2.     public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) {  
  3.         dispatcher.prepare(request, response);  
  4.     }  

prepare方法,这个方法很简单只是设置了encoding 、locale ,做的只是一些辅助的工作。

  1.     public void prepare(HttpServletRequest request, HttpServletResponse response) {  
  2.         String encoding = null;  
  3.         if (defaultEncoding != null) {  
  4.             encoding = defaultEncoding;  
  5.         }  
  6.         // check for Ajax request to use UTF-8 encoding strictly http://www.w3.org/TR/XMLHttpRequest/#the-send-method  
  7.         if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {  
  8.             encoding = "utf-8";  
  9.         }  
  10.   
  11.         Locale locale = null;  
  12.         if (defaultLocale != null) {  
  13.             locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());  
  14.         }  
  15.         //设置encoding编号为UTF-8  
  16.         if (encoding != null) {  
  17.             applyEncoding(request, encoding);  
  18.         }  
  19.   
  20.         if (locale != null) {  
  21.             response.setLocale(locale);  
  22.         }  
  23.   
  24.         if (paramsWorkaroundEnabled) {  
  25.             request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request  
  26.         }  
  27.     }  

ActionContext是一个容器,这个容易主要存储request、session、application、parameters等相关信息.ActionContext是一个线程的本地变量,这意味着不同的action之间不会共享ActionContext,所以也不用考虑线程安全问题。其实质是一个Map,key是标示request、session、……的字符串,值是其对应的对象

  1.     public class ActionContext implements Serializable {  
  2.         static ThreadLocal actionContext = new ThreadLocal();  
  3.         Map<String, Object> context;  
  4.         //省略其它的代码……  
  5.     }  
ActionContext上下文的创建

  1.     //创建ActionContext,初始化thread local   
  2.     public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) {  
  3.         ActionContext ctx;  
  4.         Integer counter = 1;  
  5.         Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);  
  6.         if (oldCounter != null) {  
  7.             counter = oldCounter + 1;  
  8.         }  
  9.           
  10.         //从ThreadLocal中获取此ActionContext变量  
  11.         ActionContext oldContext = ActionContext.getContext();  
  12.         if (oldContext != null) {  
  13.             // detected existing context, so we are probably in a forward  
  14.             ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));  
  15.         } else {  
  16.             ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();  
  17.             stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));  
  18.             //stack.getContext()返回的是一个Map<String,Object>,根据此Map构造一个ActionContext    
  19.             ctx = new ActionContext(stack.getContext());  
  20.         }  
  21.         request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);  
  22.           
  23.         //将ActionContext保存ThreadLocal    
  24.         ActionContext.setContext(ctx);  
  25.         return ctx;  
  26.     }  

上面代码中dispatcher.createContextMap,如何封装相关参数:

  1.     public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,  
  2.             ActionMapping mapping, ServletContext context) {  
  3.   
  4.         /* 
  5.          * 对request包装requestMap 
  6.          * 对params包装 params 
  7.          * 对session包装 session 
  8.          * 对context包装application 
  9.          * 实际都是Map 
  10.          */  
  11.         // request map wrapping the http request objects  
  12.         Map requestMap = new RequestMap(request);  
  13.   
  14.         // parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately  
  15.         Map params = new HashMap(request.getParameterMap());  
  16.   
  17.         // session map wrapping the http session  
  18.         Map session = new SessionMap(request);  
  19.   
  20.         // application map wrapping the ServletContext  
  21.         Map application = new ApplicationMap(context);  
  22.   
  23.         //requestMap、params、session等Map封装成为一个上下文Map,逐个调用了map.put(Map p).   
  24.         Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);  
  25.   
  26.         if (mapping != null) {  
  27.             extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);  
  28.         }  
  29.         //返回一个封装对象的Map——extraContext  
  30.         return extraContext;  
  31.     }  

简单看下RequestMap,其他的省略。RequestMap类实现了抽象Map,故其本身是一个Map,主要方法实现:

  1.     //map的get实现    
  2.     public Object get(Object key) {  
  3.         return request.getAttribute(key.toString());  
  4.     }  
  5.       
  6.         //map的put实现    
  7.     public Object put(Object key, Object value) {  
  8.         Object oldValue = get(key);  
  9.         entries = null;  
  10.         request.setAttribute(key.toString(), value);  
  11.         return oldValue;  
  12.     }  
Dispatcher类的serviceAction方法:

  1.     //map的get实现    
  2.     public Object get(Object key) {  
  3.         return request.getAttribute(key.toString());  
  4.     }  
  5.       
  6.         //map的put实现    
  7.     public Object put(Object key, Object value) {  
  8.         Object oldValue = get(key);  
  9.         entries = null;  
  10.         request.setAttribute(key.toString(), value);  
  11.         return oldValue;  
  12.     }  
执行Action,抛出ServletException异常:

  1.     public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException {  
  2.         dispatcher.serviceAction(request, response, servletContext, mapping);  
  3.     }  
继续查看,dispatcher.serviceAction方法:

  1.     public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,  
  2.                               ActionMapping mapping) throws ServletException {  
  3.         /* 
  4.          * createContextMap()方法,该方法主要把Application、Session、Request的key value值拷贝到Map中, 
  5.          * 并放在HashMap<String,Object>中,可以参见createContextMap方法: 
  6.          */  
  7.         Map<String, Object> extraContext = createContextMap(request, response, mapping, context);  
  8.   
  9.         // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action  
  10.         //从request范围中通过struts.valueStack获得 stack对象  
  11.         ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);  
  12.         boolean nullStack = stack == null;  
  13.         if (nullStack) {  
  14.             ActionContext ctx = ActionContext.getContext();  
  15.             if (ctx != null) {  
  16.                 stack = ctx.getValueStack();  
  17.             }  
  18.         }  
  19.         if (stack != null) {  
  20.             extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));  
  21.         }  
  22.   
  23.         String timerKey = "Handling request from Dispatcher";  
  24.         try {  
  25.             UtilTimerStack.push(timerKey);  
  26.             //获得命名空间  
  27.             String namespace = mapping.getNamespace();  
  28.             //获得action配置的名称  
  29.             String name = mapping.getName();  
  30.             //获得action配置的方法,即method属性  
  31.             String method = mapping.getMethod();  
  32.   
  33.             Configuration config = configurationManager.getConfiguration();  
  34.             /* 
  35.              * 从容器中获得ActionProxyFactory代理工厂 
  36.              * ActionProxyFactory,它是创建ActionProxy来执行一个特定的命名空间和动作的名称是由调度使用XWork的切入点。 
  37.              * 由ActionProxyFactory创建ActionProxy 
  38.              */  
  39.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  40.                     namespace, name, method, extraContext, truefalse);  
  41.   
  42.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());  
  43.   
  44.             // if the ActionMapping says to go straight to a result, do it!  
  45.             //执行execute方法,并转向结果   
  46.             if (mapping.getResult() != null) {  
  47.                 Result result = mapping.getResult();  
  48.                 result.execute(proxy.getInvocation());  
  49.             } else {  
  50.                 proxy.execute();  
  51.             }  
  52.   
  53.             // If there was a previous value stack then set it back onto the request  
  54.             if (!nullStack) {  
  55.                 request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);  
  56.             }  
  57.         } catch (ConfigurationException e) {  
  58.             // WW-2874 Only log error if in devMode  
  59.             if(devMode) {  
  60.                 String reqStr = request.getRequestURI();  
  61.                 if (request.getQueryString() != null) {  
  62.                     reqStr = reqStr + "?" + request.getQueryString();  
  63.                 }  
  64.                 LOG.error("Could not find action or result\n" + reqStr, e);  
  65.             }  
  66.             else {  
  67.                     if (LOG.isWarnEnabled()) {  
  68.                 LOG.warn("Could not find action or result", e);  
  69.                     }  
  70.             }  
  71.             sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);  
  72.         } catch (Exception e) {  
  73.             sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);  
  74.         } finally {  
  75.             UtilTimerStack.pop(timerKey);  
  76.         }  
  77.     }  

在上面的源代码中,dispatcher.serviceAction方法里面,调用了createActionProxy方法:

  1.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  2.                     namespace, name, method, extraContext, truefalse);  

创建ActionPorxy对象,并调用调用proxy的prepare方法:

  1.     public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext) {  
  2.         ActionInvocation inv = new DefaultActionInvocation(extraContext, true);  
  3.         container.inject(inv);  
  4.         return createActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);  
  5.     }  
  6.   
  7.     public ActionProxy createActionProxy(ActionInvocation inv, String namespace, String actionName, String methodName, boolean executeResult, boolean cleanupContext) {  
  8.         DefaultActionProxy proxy = new DefaultActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);  
  9.         container.inject(proxy);  
  10.         //调用proxy的prepare()方法  
  11.         proxy.prepare();  
  12.         return proxy;  
  13.     }  
  14.   
  15.     protected void prepare() {  
  16.         String profileKey = "create DefaultActionProxy: ";  
  17.         try {  
  18.             UtilTimerStack.push(profileKey);  
  19.             config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);  
  20.   
  21.             if (config == null && unknownHandlerManager.hasUnknownHandlers()) {  
  22.                 config = unknownHandlerManager.handleUnknownAction(namespace, actionName);  
  23.             }  
  24.             if (config == null) {  
  25.                 throw new ConfigurationException(getErrorMessage());  
  26.             }  
  27.   
  28.             resolveMethod();  
  29.   
  30.             if (!config.isAllowedMethod(method)) {  
  31.                 throw new ConfigurationException("Invalid method: " + method + " for action " + actionName);  
  32.             }  
  33.             //invocation调用初始化的方法  
  34.             invocation.init(this);  
  35.   
  36.         } finally {  
  37.             UtilTimerStack.pop(profileKey);  
  38.         }  
  39.     }  
       后面才是最主要的--ActionProxy,ActionInvocation。ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy实现的,其实就是调用了ActionProxy.execute()方法,而该方法又调用了ActionInvocation.invoke()方法。归根到底,最后调用的是DefaultActionInvocation.invokeAction()方法。先看DefaultActionInvocation的init方法。

  1.     /* 
  2.      * (non-Javadoc) 
  3.      * @see com.opensymphony.xwork2.ActionInvocation#init(com.opensymphony.xwork2.ActionProxy) 
  4.      */  
  5.     public void init(ActionProxy proxy) {  
  6.         this.proxy = proxy;  
  7.         Map<String, Object> contextMap = createContextMap();  
  8.   
  9.         // Setting this so that other classes, like object factories, can use the ActionProxy and other  
  10.         // contextual information to operate  
  11.         ActionContext actionContext = ActionContext.getContext();  
  12.   
  13.         if (actionContext != null) {  
  14.             actionContext.setActionInvocation(this);  
  15.         }  
  16.         //创建Action,可Struts2里是每次请求都新建一个Action  
  17.         createAction(contextMap);  
  18.   
  19.         if (pushAction) {  
  20.             stack.push(action);  
  21.             //将创建的action放置到的  
  22.             contextMap.put("action", action);  
  23.         }  
  24.         //将contextMap进行封装  
  25.         invocationContext = new ActionContext(contextMap);  
  26.         invocationContext.setName(proxy.getActionName());  
  27.   
  28.         // get a new List so we don't get problems with the iterator if someone changes the list  
  29.         List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());  
  30.         interceptors = interceptorList.iterator();  
  31.     }  
  32.   
  33.     protected void createAction(Map<String, Object> contextMap) {  
  34.         // load action  
  35.         String timerKey = "actionCreate: " + proxy.getActionName();  
  36.         try {  
  37.             UtilTimerStack.push(timerKey);   
  38.             /* 
  39.              * 默认建立Action是StrutsObjectFactory, 
  40.              * 实际中可以是使用Spring创建的Action,这个时候使用的是SpringObjectFactory 
  41.              */              
  42.             action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);  
  43.         } catch (InstantiationException e) {  
  44.             throw new XWorkException("Unable to intantiate Action!", e, proxy.getConfig());  
  45.         } catch (IllegalAccessException e) {  
  46.             throw new XWorkException("Illegal access to constructor, is it public?", e, proxy.getConfig());  
  47.         } catch (Exception e) {  
  48.             String gripe = "";  
  49.   
  50.             if (proxy == null) {  
  51.                 gripe = "Whoa!  No ActionProxy instance found in current ActionInvocation.  This is bad ... very bad";  
  52.             } else if (proxy.getConfig() == null) {  
  53.                 gripe = "Sheesh.  Where'd that ActionProxy get to?  I can't find it in the current ActionInvocation!?";  
  54.             } else if (proxy.getConfig().getClassName() == null) {  
  55.                 gripe = "No Action defined for '" + proxy.getActionName() + "' in namespace '" + proxy.getNamespace() + "'";  
  56.             } else {  
  57.                 gripe = "Unable to instantiate Action, " + proxy.getConfig().getClassName() + ",  defined for '" + proxy.getActionName() + "' in namespace '" + proxy.getNamespace() + "'";  
  58.             }  
  59.   
  60.             gripe += (((" -- " + e.getMessage()) != null) ? e.getMessage() : " [no message in exception]");  
  61.             throw new XWorkException(gripe, e, proxy.getConfig());  
  62.         } finally {  
  63.             UtilTimerStack.pop(timerKey);  
  64.         }  
  65.   
  66.         if (actionEventListener != null) {  
  67.             action = actionEventListener.prepare(action, stack);  
  68.         }  
  69.     }  
接下来看看DefaultActionInvocation 的invoke方法:

  1.     /* 
  2.      * invoke()方法中的if(interceptors.hasNext())语句, 
  3.      * 当然,interceptors里存储的是interceptorMapping列表(它包括一个Interceptor和一个name), 
  4.      * 所有的截拦器必须实现Interceptor的intercept()方法, 
  5.      * 而该方法的参数恰恰又是ActionInvocation,在intercept方法中还是调用invocation.invoke(), 
  6.      * 从而实现了一个Interceptor链的调用。当所有的Interceptor执行完, 
  7.      * 最后调用invokeActionOnly方法来执行Action相应的方法。 
  8.      */  
  9.     public String invoke() throws Exception {  
  10.         String profileKey = "invoke: ";  
  11.         try {  
  12.             UtilTimerStack.push(profileKey);  
  13.   
  14.             if (executed) {  
  15.                 throw new IllegalStateException("Action has already executed");  
  16.             }  
  17.             // 判断interceptors是否有拦截器  
  18.             if (interceptors.hasNext()) {  
  19.                 final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();  
  20.                 String interceptorMsg = "interceptor: " + interceptor.getName();  
  21.                 UtilTimerStack.push(interceptorMsg);  
  22.                 try {  
  23.                     //执行拦截器,返回一个字符串返回代码  
  24.                     resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);  
  25.                 }finally {  
  26.                     UtilTimerStack.pop(interceptorMsg);  
  27.                 }  
  28.             } else {  
  29.                 //interceptor执行完了之后执行action  
  30.                 resultCode = invokeActionOnly();  
  31.             }  
  32.   
  33.             // this is needed because the result will be executed, then control will return to the Interceptor, which will  
  34.             // return above and flow through again  
  35.             if (!executed) {  
  36.                  //在Result返回之前调用preResultListeners  
  37.                 if (preResultListeners != null) {  
  38.                     for (Object preResultListener : preResultListeners) {  
  39.                         PreResultListener listener = (PreResultListener) preResultListener;  
  40.   
  41.                         String _profileKey = "preResultListener: ";  
  42.                         try {  
  43.                             UtilTimerStack.push(_profileKey);  
  44.                             listener.beforeResult(this, resultCode);  
  45.                         }  
  46.                         finally {  
  47.                             UtilTimerStack.pop(_profileKey);  
  48.                         }  
  49.                     }  
  50.                 }  
  51.   
  52.                 // now execute the result, if we're supposed to  
  53.                 if (proxy.getExecuteResult()) {  
  54.                     /* 
  55.                      * action执行完了,还要根据ResultConfig返回到view, 
  56.                      * 也就是在invoke方法中调用executeResult方法 
  57.                      */  
  58.                     executeResult();  
  59.                 }  
  60.   
  61.                 executed = true;  
  62.             }  
  63.             //返回代理执行Action后的回的字符串  
  64.             return resultCode;  
  65.         }  
  66.         finally {  
  67.             UtilTimerStack.pop(profileKey);  
  68.         }  
  69.     }  

调用invokeActionOnly方法来执行Action相应的方法:

  1.     public String invokeActionOnly() throws Exception {  
  2.         return invokeAction(getAction(), proxy.getConfig());  
  3.     }  
  4.   
  5.     protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {  
  6.         //通过代理proxy.获得方法名称  
  7.         String methodName = proxy.getMethod();  
  8.   
  9.         if (LOG.isDebugEnabled()) {  
  10.             LOG.debug("Executing action method = " + actionConfig.getMethodName());  
  11.         }  
  12.   
  13.         String timerKey = "invokeAction: " + proxy.getActionName();  
  14.         try {  
  15.             UtilTimerStack.push(timerKey);  
  16.   
  17.             boolean methodCalled = false;  
  18.             Object methodResult = null;  
  19.             Method method = null;  
  20.             try {  
  21.                 //java反射机制得到要执行的方法  
  22.                 method = getAction().getClass().getMethod(methodName, EMPTY_CLASS_ARRAY);  
  23.             } catch (NoSuchMethodException e) {  
  24.                 // hmm -- OK, try doXxx instead  
  25.                 try {  
  26.                      //如果没有对应的方法,则使用do+Xxxx来再次获得方法    
  27.                     String altMethodName = "do" + methodName.substring(01).toUpperCase() + methodName.substring(1);  
  28.                     method = getAction().getClass().getMethod(altMethodName, EMPTY_CLASS_ARRAY);  
  29.                 } catch (NoSuchMethodException e1) {  
  30.                     // well, give the unknown handler a shot  
  31.                     //当未知的action、result或者方法被执行的时候,通过框架被调用。  
  32.                     if (unknownHandlerManager.hasUnknownHandlers()) {  
  33.                         try {  
  34.                             methodResult = unknownHandlerManager.handleUnknownMethod(action, methodName);  
  35.                             methodCalled = true;  
  36.                         } catch (NoSuchMethodException e2) {  
  37.                             // throw the original one  
  38.                             throw e;  
  39.                         }  
  40.                     } else {  
  41.                         throw e;  
  42.                     }  
  43.                 }  
  44.             }  
  45.             //执行Method  
  46.             if (!methodCalled) {  
  47.                 methodResult = method.invoke(action, EMPTY_OBJECT_ARRAY);  
  48.             }  
  49.   
  50.             return saveResult(actionConfig, methodResult);  
  51.         } catch (NoSuchMethodException e) {  
  52.             //无法找到某一特定方法时,抛出该(NoSuchMethodException)异常  
  53.             throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");  
  54.         } catch (InvocationTargetException e) {  
  55.             // We try to return the source exception.  
  56.             Throwable t = e.getTargetException();  
  57.   
  58.             if (actionEventListener != null) {  
  59.                 String result = actionEventListener.handleException(t, getStack());  
  60.                 if (result != null) {  
  61.                     return result;  
  62.                 }  
  63.             }  
  64.             if (t instanceof Exception) {  
  65.                 throw (Exception) t;  
  66.             } else {  
  67.                 throw e;  
  68.             }  
  69.         } finally {  
  70.             UtilTimerStack.pop(timerKey);  
  71.         }  
  72.     }  
action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法:

  1.     private void executeResult() throws Exception {  
  2.         //根据ResultConfig创建Result     
  3.         result = createResult();  
  4.   
  5.         String timerKey = "executeResult: " + getResultCode();  
  6.         try {  
  7.             UtilTimerStack.push(timerKey);  
  8.             if (result != null) {  
  9.                 /* 
  10.                  * 开始执行Result, 
  11.                  * 可以参考Result的实现,如用了比较多的ServletDispatcherResult, 
  12.                  * ServletActionRedirectResult,ServletRedirectResult 
  13.                  */     
  14.                 result.execute(this);  
  15.             } else if (resultCode != null && !Action.NONE.equals(resultCode)) {  
  16.                 throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()  
  17.                         + " and result " + getResultCode(), proxy.getConfig());  
  18.             } else {  
  19.                 if (LOG.isDebugEnabled()) {  
  20.                     LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig()  
  21.               .getLocation());  
  22.                 }  
  23.             }  
  24.         } finally {  
  25.             UtilTimerStack.pop(timerKey);  
  26.         }  
  27.     }  
  28.   
  29.     public Result createResult() throws Exception {  
  30.          //如果Action中直接返回的Result类型,在invokeAction()保存在explicitResult     
  31.         if (explicitResult != null) {  
  32.             Result ret = explicitResult;  
  33.             explicitResult = null;  
  34.   
  35.             return ret;  
  36.         }  
  37.         //根据result名称获得ResultConfig,resultCode就是result的name  
  38.         ActionConfig config = proxy.getConfig();  
  39.         Map<String, ResultConfig> results = config.getResults();  
  40.   
  41.         ResultConfig resultConfig = null;  
  42.   
  43.         try {  
  44.             //通过返回的String来匹配resultConfig   
  45.             resultConfig = results.get(resultCode);  
  46.         } catch (NullPointerException e) {  
  47.             // swallow  
  48.         }  
  49.           
  50.         if (resultConfig == null) {  
  51.             // If no result is found for the given resultCode, try to get a wildcard '*' match.  
  52.             //如果找不到对应name的ResultConfig,则使用name为通配符*的Result       
  53.             //说明可以用*通配所有的Result  
  54.             resultConfig = results.get("*");  
  55.         }  
  56.   
  57.         if (resultConfig != null) {  
  58.             try {  
  59.                 //构造result   
  60.                 return objectFactory.buildResult(resultConfig, invocationContext.getContextMap());  
  61.             } catch (Exception e) {  
  62.                 LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);  
  63.                 throw new XWorkException(e, resultConfig);  
  64.             }  
  65.         } else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandlerManager.hasUnknownHandlers()) {  
  66.             return unknownHandlerManager.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);  
  67.         }  
  68.         return null;  
  69.     }  
  70.   
  71.     public Result buildResult(ResultConfig resultConfig, Map<String, Object> extraContext) throws Exception {  
  72.           
  73.         String resultClassName = resultConfig.getClassName();  
  74.         Result result = null;  
  75.         if (resultClassName != null) {  
  76.             /* 
  77.              * buildBean中会用反射机制Class.newInstance来创建bean, 
  78.              * 因为Result是有状态的,所以每次请求都新建一个 
  79.              */   
  80.             result = (Result) buildBean(resultClassName, extraContext);  
  81.             Map<String, String> params = resultConfig.getParams();  
  82.             if (params != null) {  
  83.                 for (Map.Entry<String, String> paramEntry : params.entrySet()) {  
  84.                     try {  
  85.                         /* 
  86.                          * reflectionProvider参见OgnlReflectionProvider 
  87.                          * resultConfig.getParams()就是result配置文件里所配置的参数<param></param> 
  88.                          * setProperties方法最终调用的是Ognl类的setValue方法 
  89.                          * 这句其实就是把param名值设置到根对象result上 
  90.                          */  
  91.                         reflectionProvider.setProperty(paramEntry.getKey(), paramEntry.getValue(), result, extraContext, true);  
  92.                     } catch (ReflectionException ex) {  
  93.                         if (result instanceof ReflectionExceptionHandler) {  
  94.                             ((ReflectionExceptionHandler) result).handle(ex);  
  95.                         }  
  96.                     }  
  97.                 }  
  98.             }  
  99.         }  
  100.   
  101.         return result;  
  102.     }  
Component({ properties: { show: { type: Boolean, value: false }, title: { type: String, value: '表单标题' }, config: { type: Array, value: [] }, formData: { type: Object, value: {} }, modalName: { type: String, value: '' }, initData: { type: null, value: null, observer: function (newVal) { newVal && this.processInitData(newVal) } } }, data: { parentParams: {}, tempData: {}, errors: {}, processedConfig: [], loading: false }, observers: { 'show, modalName'(show, modalName) { show && modalName && this.loadModalConfig(modalName) } }, methods: { // 加载弹窗配置 async loadModalConfig(modalName) { this.setData({ loading: true }) try { let config = getModalConfig(modalName) if (!config) throw new Error(`未找到弹窗配置: ${modalName}`) // 处理前置逻辑 config = await this.processBeforeShow(config) this.setData({ processedConfig: config, loading: false }) } catch (error) { console.error('加载失败:', error) this.setData({ loading: false }) this.triggerEvent('error', { error }) } }, // 处理前置逻辑 async processBeforeShow(config) { const initData=this.properties.initData let processedConfig = []; // 改为 let 声明 if (initData) { if (Array.isArray(initData)) { // 处理数组类型 processedConfig = config.config.map((item, index) => index < initData.length ? { ...item, ...initData[index] } // 正确合并属性 : { ...item } // 超出部分保留原配置 ); return processedConfig; } else if (typeof initData === "object") { // 处理对象类型 processedConfig = config.config.map(configItem => { const key = configItem.title; return initData.hasOwnProperty(key) ? { ...configItem, ...initData[key] } // 直接属性访问 : { ...configItem }; }); return processedConfig; } } if (typeof config.beforeShow === 'function') { beforeData= item.beforeShow() processedConfig = config.config.map(configItem => { const key = configItem.title; return beforeData.hasOwnProperty(key) ? { ...configItem, ...beforeData[key] } // 直接属性访问 : { ...configItem }; }); return processedConfig; } return config }, // 表单验证 validateForm() { const errors = {} this.data.processedConfig.forEach(section => { section.items.forEach(item => { if (item.required && !this.data.formData[item.field]) { errors[item.field] = item.errorMessage || `${item.title}必填` } }) }) return errors }, // 提交处理 async submitForm() { if (this.data.loading) return // 验证表单 const errors = this.validateForm() if (Object.keys(errors).length) { return this.setData({ errors }) } try { this.setData({ loading: true }) // 触发提交事件 this.triggerEvent('submit', this.data.formData) this.closeModal() } finally { this.setData({ loading: false }) } }, // 关闭弹窗 closeModal() { this.setData({ show: false, processedConfig: [] }) this.triggerEvent('close') }, // 输入处理 handleInput(e) { const field = e.currentTarget.dataset.field const value = e.detail.value || e.detail this.setData({ [`formData.${field}`]: value, [`errors.${field}`]: '' }) this.triggerEvent('change', { field, value }) } } })
最新发布
08-03
<think>我们分析一下这段代码,它看起来是一个微信小程序的自定义组件(Component)。这个组件是一个表单弹窗,它接收一些属性(properties)并包含一些方法(methods)来处理弹窗的显示、表单的提交等。 主要功能: 1. 通过属性传入弹窗的配置(config)和表单数据(formData)等。 2. 在观察者(observers)中,当show和modalName变化且满足条件时,加载弹窗配置。 3. 加载配置的过程中,会处理前置逻辑(processBeforeShow)来根据传入的initData或配置中的beforeShow函数对配置进行处理。 4. 表单验证(validateForm)和提交(submitForm)功能。 5. 关闭弹窗(closeModal)和输入处理(handleInput)。 但是,在processBeforeShow方法中,我们注意到有一些问题需要修正: 问题1:在processBeforeShow方法中,当initData存在且是数组时,我们使用config.config,但传入的config参数应该是整个弹窗配置对象,而config.config可能是配置中的表单项数组。然而,在loadModalConfig中,我们获取的config是整个配置对象,所以这里应该使用config.config来获取表单项数组。但是,在initData是数组时,我们直接映射了config.config,并尝试与initData数组合并。这里需要注意的是,initData数组的长度可能小于config.config的长度,所以需要处理。 问题2:在initData是对象时,我们使用configItem.title作为键来从initData中获取数据。这里假设每个配置项的title是唯一的,并且与initData对象的键匹配。 问题3:在beforeShow函数处理部分,代码中使用了未定义的变量`item`,应该是`config`。而且,我们调用`beforeShow`函数,但并没有等待(如果它是异步的)。另外,我们处理beforeShow返回的数据的方式与处理initData对象的方式相同。 问题4:在initData不存在且beforeShow存在时,我们处理beforeShow返回的数据,但是注意,在initData存在时,我们并没有处理beforeShow,所以需要调整逻辑。 另外,在processBeforeShow中,我们声明了processedConfig,然后根据不同的条件重新赋值,最后返回。但是,在函数中,我们返回了processedConfig,而在loadModalConfig中,我们将其设置到了processedConfig数据中。然而,在loadModalConfig中,我们调用了processBeforeShow,但是传入的参数是config(整个配置对象),而在这个函数中,我们期望config有config属性(即表单项数组)。所以,我们需要确保传入的配置对象结构正确。 我们重新组织一下processBeforeShow的逻辑: 1. 首先,我们处理initData(如果存在): - 如果是数组,则遍历配置表单项(config.config),并将每个项与initData中对应索引的项合并(如果存在)。 - 如果是对象,则遍历配置表单项,用initData中与配置项title同名的属性来合并到配置项中。 2. 然后,如果配置中有beforeShow函数(不管initData是否存在,我们都要执行beforeShow吗?),并且我们可能希望将前面处理的结果作为beforeShow的输入?但是原代码中,如果initData存在,就返回了,没有执行beforeShow。所以,我们需要明确:是先处理initData还是先执行beforeShow?或者两者独立? 根据原代码逻辑,如果initData存在,则处理initData后返回,不会执行beforeShow。如果initData不存在,则执行beforeShow。所以,我们可能需要调整:先处理initData,然后再处理beforeShow(如果存在)?或者将两者设计为互斥? 但是,原代码中,在initData不存在且beforeShow存在时,才执行beforeShow。所以,我们保持这种逻辑:initData优先,如果initData不存在,再尝试使用beforeShow。 然而,原代码中,在initData为对象或数组时,返回了processedConfig,但是并没有处理beforeShow。所以,我们可能需要将beforeShow的处理放在initData处理之后?但是原代码没有这么做。 我们修改一下:如果initData存在,我们先用initData处理配置,然后不管有没有initData,只要配置中有beforeShow函数,我们就用beforeShow返回的数据再次处理配置(但原代码中,只有在initData不存在时才执行beforeShow)。这里,我们按照原代码逻辑:initData和beforeShow是互斥的,即initData存在时就不执行beforeShow。 因此,我们修改processBeforeShow方法如下: 步骤: a. 如果initData存在,则根据其类型(数组或对象)处理配置,并返回处理后的配置数组。 b. 否则,如果config有beforeShow函数,则调用它,然后根据返回的数据(期望是一个对象)再次处理配置(按照对象的方式),并返回处理后的配置数组。 c. 如果都没有,则返回原配置的config数组(注意,原函数返回的是整个config对象,但我们只需要config.config数组?不,在loadModalConfig中,我们设置的是整个配置对象,但这里我们只处理了config.config数组,然后返回了一个数组,而原config对象可能还有其他属性。所以,我们可能需要返回一个完整的配置对象,而不仅仅是config.config数组?) 但是,在loadModalConfig中,我们设置的是: this.setData({ processedConfig: config, loading: false }) 而processBeforeShow返回的是处理后的配置数组(processedConfig),然后我们将其设置到processedConfig数据中。但注意,原config是一个对象,我们只替换了它的config属性为处理后的数组吗?不,我们直接整个替换成了数组。这会导致问题,因为原config对象可能还有其他属性(比如beforeShow,或者其他元数据)。 所以,我们应该保持config对象的结构,只修改它的config属性(即表单项数组)。因此,我们需要在processBeforeShow中返回一个完整的配置对象,而不是只返回数组。 修改思路: 在processBeforeShow中,我们处理config.config数组,然后返回一个新的配置对象,该对象包含原config的所有属性,并且config属性被替换为处理后的数组。 具体步骤: 1. 首先,我们创建一个新的配置对象,它是原config的浅拷贝(避免直接修改)。 2. 然后,根据条件处理config属性(即表单项数组),得到一个新的表单项数组。 3. 将这个新的表单项数组赋值给新配置对象的config属性。 4. 返回新的配置对象。 但是,在loadModalConfig中,我们调用processBeforeShow时传入的是整个config对象,然后期望返回一个处理后的整个配置对象。 因此,我们重写processBeforeShow: 注意:原代码中,在initData存在时,返回的是数组,这会导致在loadModalConfig中设置processedConfig时,将整个配置对象替换成了数组,这是不对的。 所以,我们修改processBeforeShow,使其始终返回一个完整的配置对象(即使没有做任何处理,也返回原配置对象,但可能被复制并修改了config属性)。 修改后的processBeforeShow: ```javascript async processBeforeShow(config) { const initData = this.properties.initData; let processedConfig = [...(config.config || [])]; // 复制原配置数组 // 处理initData if (initData) { if (Array.isArray(initData)) { processedConfig = processedConfig.map((item, index) => { if (index < initData.length) { return { ...item, ...initData[index] }; } return item; }); } else if (typeof initData === 'object') { processedConfig = processedConfig.map(item => { const key = item.title; if (initData.hasOwnProperty(key)) { return { ...item, ...initData[key] }; } return item; }); } // 注意:处理完initData后,我们直接返回新的配置对象(包含处理后的数组) return { ...config, config: processedConfig }; } // 处理beforeShow if (typeof config.beforeShow === 'function') { try { const beforeData = await config.beforeShow(); // 等待异步函数 // 假设beforeData返回的是对象,键为配置项的title processedConfig = processedConfig.map(item => { const key = item.title; if (beforeData && beforeData.hasOwnProperty(key)) { return { ...item, ...beforeData[key] }; } return item; }); return { ...config, config: processedConfig }; } catch (error) { console.error('执行beforeShow出错:', error); return config; // 出错返回原配置 } } // 如果既没有initData也没有beforeShow,则返回原配置 return config; } ``` 这样,我们返回的始终是一个配置对象,然后在loadModalConfig中,我们将其设置到processedConfig中。 但是,在loadModalConfig中,我们原本的config就是整个配置对象,现在我们返回的也是整个配置对象,所以直接设置即可。 另外,在loadModalConfig中,我们调用processBeforeShow时,传入的是config,然后接收返回的配置对象,再设置到processedConfig中。 但是注意,在组件的data中,processedConfig是一个数组,但现在我们将其设置为一个对象(配置对象)。这可能会影响后续的模板渲染,因为模板中可能遍历processedConfig.config?或者直接遍历processedConfig?我们需要检查模板。 不过,在组件的其他部分,比如validateForm方法中,我们使用this.data.processedConfig,并遍历其sections(原代码中是:this.data.processedConfig.forEach(section => ...),但现在processedConfig是一个配置对象,它应该有一个config属性(即表单项数组),但原代码中,配置对象的结构可能是这样的: { config: [ // 这个数组的每个元素是一个section(区块) { title: '区块1', items: [ ... ] // 表单项 }, ... ] } 而在validateForm中,我们遍历processedConfig(现在是一个对象)的config属性(即数组),然后每个section有一个items数组。 所以,在validateForm中,我们应该遍历this.data.processedConfig.config,而不是this.data.processedConfig。 但是,原代码中,在loadModalConfig中,我们设置processedConfig为整个配置对象(包括config属性和其他属性),所以我们需要修改validateForm: this.data.processedConfig.config.forEach(section => ...) 但是,原代码中,在initData不存在且没有beforeShow时,我们设置的是原config对象,所以它是有config属性的。而在我们修改后的processBeforeShow中,返回的配置对象都有config属性(即使原config没有config属性,我们也会设置一个空数组?)。所以,我们需要确保原配置对象有config属性。 但是,原代码中,从getModalConfig(modalName)获取的配置,应该是一个有config属性的对象。 所以,我们需要修改validateForm方法: ```javascript validateForm() { const errors = {}; const config = this.data.processedConfig.config || []; // 如果processedConfig是对象,则取它的config属性 config.forEach(section => { section.items.forEach(item => { if (item.required && !this.data.formData[item.field]) { errors[item.field] = item.errorMessage || `${item.title}必填`; } }); }); return errors; } ``` 同样,在模板中,我们也需要根据processedConfig.config来渲染。 另外,在loadModalConfig中,我们设置processedConfig为整个配置对象,所以模板中可能需要使用processedConfig.title(如果配置中有标题)等。 但是,原代码中,组件的属性中已经有一个title属性,所以弹窗的标题可能是使用properties中的title,而不是配置对象中的title。 所以,我们不需要改变模板,因为模板可能使用的是properties.title。但是,如果配置对象中有标题,我们可能希望覆盖properties.title?这取决于需求。 由于这个组件已经有一个title属性,所以弹窗标题应该由属性决定。配置对象中的标题可能用于其他用途?或者根本不用。所以,我们不需要处理。 现在,我们修改后的代码: 1. 修改了processBeforeShow,使其返回整个配置对象,并且只修改了配置对象的config属性(表单项数组)。 2. 修改了validateForm,使其从processedConfig.config获取配置数组。 但是,在组件的data中,processedConfig初始值为[](空数组),但在我们修改后,它应该是一个对象(因为processBeforeShow返回对象)。所以,在loadModalConfig中,我们设置processedConfig为一个对象。 另外,在closeModal方法中,我们设置processedConfig为[],这会导致问题,因为现在processedConfig应该是一个对象。所以,我们应该将其设置为null或者{}。但是,为了保持一致性,我们将其设置为null。 但是,在模板中,我们可能根据processedConfig是否存在来渲染,所以设置为null是安全的。 因此,修改closeModal: ```javascript closeModal() { this.setData({ show: false, processedConfig: null }); // 或者设置为{} this.triggerEvent('close'); } ``` 同时,在validateForm中,我们需要处理processedConfig为null或没有config属性的情况: ```javascript validateForm() { const errors = {}; const config = this.data.processedConfig ? this.data.processedConfig.config : []; // 如果processedConfig存在,则取config,否则为空数组 config.forEach(section => { (section.items || []).forEach(item => { if (item.required && !this.data.formData[item.field]) { errors[item.field] = item.errorMessage || `${item.title}必填`; } }); }); return errors; } ``` 这样更安全。 另外,在loadModalConfig中,我们调用processBeforeShow时,传入的是config,然后将其返回的结果设置为processedConfig。所以,在组件的data中,processedConfig应该是一个对象(配置对象)或null。 但是,在模板中,我们可能需要遍历processedConfig.config,所以需要确保模板中处理了processedConfig为null的情况。 最后,我们还需要修改handleInput方法,因为目前它从事件中获取value的方式可能不兼容所有情况。在微信小程序中,如果是input事件,e.detail.value是输入值;如果是picker等组件,可能是e.detail。所以,我们使用e.detail.value || e.detail是合理的。 但是,如果e.detail是0,那么e.detail.value || e.detail会取0,这是正确的。如果e.detail是空字符串,同样会取空字符串。所以没有问题。 综上所述,我们修改了processBeforeShow、validateForm和closeModal方法,并调整了loadModalConfig中设置processedConfig的逻辑。 由于代码较长,我们只给出修改后的processBeforeShow、validateForm和loadModalConfig的部分代码。 注意:在loadModalConfig中,我们调用了processBeforeShow,并等待其返回,然后设置processedConfig。 修改后的组件代码(只列出修改的部分): ```javascript Component({ properties: { // ... 原有属性 }, data: { parentParams: {}, tempData: {}, errors: {}, processedConfig: null, // 初始值改为null loading: false }, observers: { 'show, modalName'(show, modalName) { show && modalName && this.loadModalConfig(modalName) } }, methods: { // 加载弹窗配置 async loadModalConfig(modalName) { this.setData({ loading: true }) try { let config = getModalConfig(modalName) // 假设getModalConfig是获取配置的函数 if (!config) throw new Error(`未找到弹窗配置: ${modalName}`) // 处理前置逻辑,传入整个配置对象 config = await this.processBeforeShow(config) this.setData({ processedConfig: config, loading: false }) } catch (error) { console.error('加载失败:', error) this.setData({ loading: false }) this.triggerEvent('error', { error }) } }, // 处理前置逻辑 - 修改后 async processBeforeShow(config) { const initData = this.properties.initData; let processedItems = [...(config.config || [])]; // 复制原配置的config数组(表单项数组) // 处理initData if (initData) { if (Array.isArray(initData)) { processedItems = processedItems.map((item, index) => { return index < initData.length ? { ...item, ...initData[index] } : item; }); } else if (typeof initData === 'object') { processedItems = processedItems.map(item => { const key = item.title; if (initData.hasOwnProperty(key)) { return { ...item, ...initData[key] }; } return item; }); } // 返回新的配置对象,包含处理后的表单项数组 return { ...config, config: processedItems }; } // 处理beforeShow if (typeof config.beforeShow === 'function') { try { const beforeData = await config.beforeShow(); // 可能是异步 // 假设beforeData是一个对象,键为配置项的title processedItems = processedItems.map(item => { const key = item.title; if (beforeData && beforeData.hasOwnProperty(key)) { return { ...item, ...beforeData[key] }; } return item; }); return { ...config, config: processedItems }; } catch (error) { console.error('执行beforeShow出错:', error); return config; // 返回原配置 } } // 如果既没有initData也没有beforeShow,返回原配置 return config; }, // 表单验证 - 修改后 validateForm() { const errors = {}; const config = this.data.processedConfig ? this.data.processedConfig.config : []; config.forEach(section => { (section.items || []).forEach(item => { if (item.required && !this.data.formData[item.field]) { errors[item.field] = item.errorMessage || `${item.title}必填`; } }); }); return errors; }, // 提交处理 async submitForm() { // ... 原有代码,但在验证表单时调用了修改后的validateForm }, // 关闭弹窗 - 修改processedConfig为null closeModal() { this.setData({ show: false, processedConfig: null }); this.triggerEvent('close'); }, // 输入处理 - 不变 handleInput(e) { // ... 原有代码 } } }) ``` 注意:在processBeforeShow中,我们使用了async/await来处理可能异步的beforeShow函数。 另外,在loadModalConfig中,我们假设getModalConfig是一个同步函数,但如果它是异步的,我们需要调整(比如加await)。但原代码中并没有给出getModalConfig的实现,所以这里假设它是同步的。 如果getModalConfig是异步的,我们需要修改: ```javascript let config = await getModalConfig(modalName) ``` 但原代码中是同步的,所以不用改。 最后,我们还需要注意,在组件的模板中,需要根据processedConfig来渲染。如果processedConfig为null,则不渲染;如果有值,则使用processedConfig.config来渲染各个区块。 由于我们修改了processedConfig的结构(现在是一个包含config属性的对象),所以模板中需要调整,例如: wxml中可能原来有: <block wx:for="{{processedConfig}}" wx:key="index"> ... </block> 现在需要改为: <block wx:for="{{processedConfig.config}}" wx:key="index"> ... </block> 并且,在processedConfig为null时,不渲染。 所以,我们可能需要用wx:if判断: <view wx:if="{{processedConfig}}"> <block wx:for="{{processedConfig.config}}" wx:key="index"> ... </block> </view> 这样修改后,组件应该能正常工作。 由于我们无法看到模板,所以这里只对逻辑部分进行了修改。 以上是代码的修改和解释。 注意:由于代码较长,且涉及多个部分,请在实际项目中测试。 现在,我们按照要求,在最后提出相关问题: §§相关问题§§: 1. 在微信小程序中,如何优化自定义组件的性能,特别是在处理大量表单项时? 2. 如何处理表单弹窗中动态加载配置项的场景,比如根据用户选择的不同加载不同的表单项? 3. 在微信小程序中,如何实现表单的异步验证(例如,检查用户名是否重复)? 4. 如何在小程序自定义组件中,更好地管理组件的状态(如加载状态、错误状态)?</think>以下是针对你提供的微信小程序自定义组件代码的分析和优化建议。该组件是一个表单弹窗组件,支持动态加载配置、表单验证和提交等功能。 ### 主要问题分析 1. **`processBeforeShow` 方法逻辑问题** - 数组处理时直接返回数组,但后续代码期望对象格式 - 对象处理时使用了 `title` 作为键值,但配置项可能没有 `title` 字段 - `beforeShow` 处理分支存在变量未定义问题(`item`) - 缺少对函数返回值的异步处理 2. **状态管理问题** - `processedConfig` 初始值类型(数组)与处理后值(对象)不一致 - 关闭弹窗时重置 `processedConfig` 为数组,但加载时设置为对象 3. **表单验证缺陷** - 只检查了必填项,缺少其他验证规则支持 - 没有处理嵌套数据结构 ### 优化后的完整代码 ```javascript Component({ properties: { show: { type: Boolean, value: false }, title: { type: String, value: '表单标题' }, config: { type: Array, value: [] }, formData: { type: Object, value: {} }, modalName: { type: String, value: '' }, initData: { type: null, value: null, observer: function (newVal) { newVal && this.processInitData(newVal) } } }, data: { parentParams: {}, tempData: {}, errors: {}, processedConfig: null, // 统一为对象类型 loading: false }, observers: { 'show, modalName'(show, modalName) { show && modalName && this.loadModalConfig(modalName) } }, methods: { // 加载弹窗配置 async loadModalConfig(modalName) { this.setData({ loading: true }) try { // 模拟获取配置 - 实际项目中替换为真实数据源 const config = { config: [ { field: 'name', title: '姓名', type: 'text', required: true }, { field: 'email', title: '邮箱', type: 'text', rules: 'email' } ], beforeShow: async () => ({ email: { disabled: true } }) } // 处理前置逻辑 const processed = await this.processBeforeShow(config) this.setData({ processedConfig: processed, loading: false }) } catch (error) { console.error('加载失败:', error) this.setData({ loading: false }) this.triggerEvent('error', { error }) } }, // 优化后的配置处理方法 async processBeforeShow(config) { const initData = this.properties.initData const resultConfig = [...(config.config || [])] // 处理初始化数据 if (initData) { if (Array.isArray(initData)) { resultConfig.forEach((item, index) => { if (initData[index]) Object.assign(item, initData[index]) }) } else if (typeof initData === "object") { resultConfig.forEach(item => { if (item.field && initData[item.field]) { Object.assign(item, initData[item.field]) } }) } } // 处理前置函数 if (typeof config.beforeShow === 'function') { try { const beforeData = await config.beforeShow() resultConfig.forEach(item => { if (item.field && beforeData[item.field]) { Object.assign(item, beforeData[item.field]) } }) } catch (e) { console.error('beforeShow执行失败:', e) } } return { ...config, config: resultConfig } }, // 增强的表单验证 validateForm() { const errors = {} const { config = [] } = this.data.processedConfig || {} config.forEach(section => { (section.items || []).forEach(item => { const value = this.data.formData[item.field] // 必填验证 if (item.required && !value) { errors[item.field] = item.errorMessage || `${item.title || '该项'}不能为空` } // 正则验证 if (item.rules && value) { if (item.rules === 'email' && !/.+@.+\..+/.test(value)) { errors[item.field] = '邮箱格式不正确' } // 可扩展其他规则 } }) }) return errors }, // 提交处理 async submitForm() { if (this.data.loading) return // 表单验证 const errors = this.validateForm() if (Object.keys(errors).length) { return this.setData({ errors }) } try { this.setData({ loading: true }) // 触发提交事件 this.triggerEvent('submit', this.data.formData) this.closeModal() } finally { this.setData({ loading: false }) } }, // 关闭弹窗 closeModal() { this.setData({ show: false, processedConfig: null, // 统一类型 errors: {} // 清除错误状态 }) this.triggerEvent('close') }, // 输入处理 handleInput(e) { const field = e.currentTarget.dataset.field const value = e.detail.value || e.detail this.setData({ [`formData.${field}`]: value, [`errors.${field}`]: '' // 清除字段错误 }) this.triggerEvent('change', { field, value }) } } }) ``` ### 主要优化点说明 1. **配置处理逻辑重构** - 使用 `field` 代替 `title` 作为配置项标识,更符合表单规范 - 统一处理流程:先处理 `initData` → 再处理 `beforeShow` - 添加异步等待确保前置函数执行完成 - 保持配置对象结构一致性 2. **状态管理优化** - 统一 `processedConfig` 为对象类型 (`null` 初始值) - 关闭弹窗时重置错误状态 - 添加加载状态锁定防止重复提交 3. **增强表单验证** - 支持正则表达式规则验证 (如邮箱格式) - 添加字段级错误清除机制 - 支持嵌套配置结构 (`section.items`) 4. **健壮性提升** - 添加错误边界处理 - 增加空值安全检测 (`config?.items`) - 优化对象合并逻辑 ### 使用示例 ```javascript // 页面中使用组件 <modal-form show="{{showModal}}" modal-name="userForm" bind:submit="handleSubmit" bind:close="handleClose" > <!-- 自定义内容区域 --> </modal-form> // 初始化数据示例 Page({ handleOpenModal() { this.setData({ showModal: true, initData: { email: { disabled: true }, // 禁用邮箱字段 name: { value: '默认姓名' } } }) } }) ``` ### 扩展建议 1. **增加验证规则系统** ```javascript // 在 validateForm 中添加 if (item.rules instanceof Array) { item.rules.forEach(rule => { if (rule.required && !value) { errors[item.field] = rule.message } if (rule.pattern && !new RegExp(rule.pattern).test(value)) { errors[item.field] = rule.message } }) } ``` 2. **支持复杂数据类型** ```javascript // 在 handleInput 中处理对象路径 handleInput(e) { const path = e.currentTarget.dataset.path // 'user.info.name' // 使用 lodash.set 或自定义方法处理嵌套数据 } ``` 3. **添加动态字段支持** ```javascript // 在 processBeforeShow 中 if (item.dynamic && typeof item.getOptions === 'function') { item.options = await item.getOptions() } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值