struts2 自定义tiles.xml文件路径

struts2+tiles时,tiles.xml默认是放在文件夹/web-inf/下面,使用ServletContext的方法查找,一般不需要改动,但是遇到BT的要求需要自定义这个titles的路径查找方式时,可以使用如下方法:
1:在web.xml里面配置自定义监听器:


Xml代码

  1. <listener> 
  2.        <listener-class>demo.MyStrutsTilesListener</listener-class> 
  3.    </listener> 

2:实现demo.MyStrutsTilesListener这个类,它继承自org.apache.struts2.tiles.StrutsTilesListener,重载方法


Java代码

  1. protected ServletContext decorate(ServletContext context)  
  2. { 
  3.    Map<String, String> INIT = new HashMap<String, String>(); 
  4.        INIT.put(TilesContainerFactory.CONTAINER_FACTORY_INIT_PARAM,  StrutsTilesContainerFactory.class.getName()); 
  5.    ServletContext servletContext = new MyTilesContext(context,INIT); 
  6.         
  7.    return servletContext; 
  8. } 

3:实现MyTilesContext:

Java代码

  1. public class CyberTilesContext extends ConfiguredServletContext 
  2. { 
  3.    public static final String PREFIX = "file:///"; 
  4.     
  5.    public CyberTilesContext(ServletContext context, Map<String, String> initParameters) 
  6.    { 
  7.        super(context, initParameters); 
  8.    } 
  9.  
  10.    @Override 
  11.    public URL getResource(String string) throws MalformedURLException 
  12.    { 
  13.        if (!string.startsWith(PREFIX)) 
  14.        { 
  15.            return super.getResource(string);    
  16.        } 
  17.         
  18.        String path = string.substring(PREFIX.length()); 
  19.        File file = new File(path); 
  20.        if (!file.exists()) 
  21.        { 
  22.            throw new RuntimeException("file " + path + " not founded."); 
  23.        } 
  24.         
  25.        return file.toURI().toURL(); 
  26.    } 
  27. } 

通过重载getResource方法可以定制自己所需要的查找tiles.xml的方法,上面的例子就是实现以file:///开头查找绝对路径下的tiles.xml。

PS:很不喜欢struts2,对于我来讲,它不适合快速开发,它也不适合大型网站。


Total views.

© 2013 - 2025. All rights reserved.

Powered by Hydejack v6.6.1