使struts2配置项支持通配符,无需再<include>!

2 篇文章 0 订阅

看struts2的源码,是无法进行使用通配符配置文件配置的,我们只能老老实实的在配置文件中写入一个有一个的include。虽然可以在多个配置文件中进行include嵌套编写。但总归还是需要写滴。

要做到使用通配符的方式,按照某种规则来自动查找配置文件并加载,则需要我们struts2的进行扩展。

 

org.apache.struts2.dispatcher.Dispatcher的init_TraditionalXmlConfigurations()方法是对配置文件进行读取的入口,我们在方法的最后可以增加通配读取方法:init_TraditionalXmlConfigurationsWithExtResource();

 

/**
  * 扩展资源,增加了对通配符的支持
  */
 private void init_TraditionalXmlConfigurationsWithExtResource(){
  String configPaths = initParams.get("extConfig");
  System.out.println("struts param configPaths:"+configPaths);
  if(configPaths!=null){
    String[] files = configPaths.split("\\s*[,]\\s*");
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    for (String file : files) {
     System.out.println("struts ext file:"+file);
     try {
     Resource[] resources = resolver.getResources(file);
      for (Resource resource: resources) {
       URL url  = resource.getURL();
       String filePath =resource.getFilename();
       File f =resource.getFile();
      
       configurationManager.addConfigurationProvider(createStrutsXmlSpringClassPathConfigurationProvider(resource, false, servletContext));
      }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
       }
  }
  
  
 }

  protected StrutsXmlSpringClassPathConfigurationProvider createStrutsXmlSpringClassPathConfigurationProvider(Resource resource, boolean errorIfMissing, ServletContext ctx) throws IOException {
         return new StrutsXmlSpringClassPathConfigurationProvider(resource, errorIfMissing, ctx);
  }

 

这里我们使用的是spring的通配加载功能来实现的,具体的class如下:

/*
 * $Id: StrutsXmlConfigurationProvider.java 762875 2009-04-07 17:56:30Z musachy $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.struts2.config;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.core.io.Resource;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.inject.Context;
import com.opensymphony.xwork2.inject.Factory;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * Override Xwork class so we can use an arbitrary config file
 */
public class StrutsXmlSpringClassPathConfigurationProvider extends XmlConfigurationProvider {

    private static final Logger LOG = LoggerFactory.getLogger(StrutsXmlSpringClassPathConfigurationProvider.class);
    private File baseDir = null;
    private String filename;
    private String reloadKey;
    private ServletContext servletContext;

 

    /**
     * Constructs the configuration provider
     *
     * @param filename The filename to look for
     * @param errorIfMissing If we should throw an exception if the file can't be found
     * @param ctx Our ServletContext
     * @throws IOException
     */
    public StrutsXmlSpringClassPathConfigurationProvider(Resource  resource, boolean errorIfMissing, ServletContext ctx) throws IOException {
     
     super(resource.getURL().toString(), errorIfMissing);
     //String f =new File(resource.getURI()).getName();
     System.out.println("StrutsXmlSpringClassPathConfigurationProvider:"+resource.getURL().toString());
        this.servletContext = ctx;
        this.filename = resource.getURL().toString();
        reloadKey = "configurationReload-"+filename;
        Map<String,String> dtdMappings = new HashMap<String,String>(getDtdMappings());
        dtdMappings.put("-//Apache Software Foundation//DTD Struts Configuration 2.0//EN", "struts-2.0.dtd");
        dtdMappings.put("-//Apache Software Foundation//DTD Struts Configuration 2.1//EN", "struts-2.1.dtd");
        dtdMappings.put("-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN", "struts-2.1.7.dtd");
        setDtdMappings(dtdMappings);
      
    }
   
    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.config.providers.XmlConfigurationProvider#register(com.opensymphony.xwork2.inject.ContainerBuilder, java.util.Properties)
     */
    @Override
    public void register(ContainerBuilder containerBuilder, LocatableProperties props) throws ConfigurationException {
        if (servletContext != null && !containerBuilder.contains(ServletContext.class)) {
            containerBuilder.factory(ServletContext.class, new Factory<ServletContext>() {
                public ServletContext create(Context context) throws Exception {
                    return servletContext;
                }
            });
        }
        super.register(containerBuilder, props);
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.config.providers.XmlConfigurationProvider#init(com.opensymphony.xwork2.config.Configuration)
     */
    @Override
    public void loadPackages() {
        ActionContext ctx = ActionContext.getContext();
        ctx.put(reloadKey, Boolean.TRUE);
        super.loadPackages();
    }

    /**
     * Look for the configuration file on the classpath and in the file system
     *
     * @param fileName The file name to retrieve
     * @see com.opensymphony.xwork2.config.providers.XmlConfigurationProvider#getConfigurationUrls
     */
    @Override
    protected Iterator<URL> getConfigurationUrls(String fileName) throws IOException {
     
        URL url =new URL(fileName);
      
       
        List<URL> list = new ArrayList<URL>();
        list.add(url);
        return list.iterator();
       
    }

   
    /**
     * Overrides needs reload to ensure it is only checked once per request
     */
    @Override
    public boolean needsReload() {
        ActionContext ctx = ActionContext.getContext();
        if (ctx != null) {
            return ctx.get(reloadKey) == null && super.needsReload();
        } else {
            return super.needsReload();
        }

    }
   
    public String toString() {
        return ("Struts XML configuration provider ("+filename+")");
    }
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值