在Web项目中,资源文件同样位于src/main/resources/目录下,他们经处理后会位于WAR包的WEB-INF/classes目录下,这也是Java代码编译打包后的目录。也就是说,这类资源文件在打包过后位于应用程序的classpath中。Web项目中还有另外一类资源文件,默认他们的源码位于src/main/webapp/目录,经打包后位于WAR包的根目录。例如,一个Web项目的css源码文件在src/main/webapp/css/目录,项目打包后可以在WAR包的css/目录下找到对应的css文件。这一类资源文件称作web资源文件,他们在打包过后不位于应用程序的classpath中。
与一般的资源文件一样,web资源文件默认不会被过滤。开启一般资源文件的过滤也不会影响到web资源文件。
不过有的时候,我们可能希望在构建项目的时候,为不同的客户使用不一样的资源文件(例如客户的log图片不同,或者css主题不同)。这时可以在web资源文件中使用Maven属性,例如用${client.logo}表示客户的logo图片,用${client.theme}表示客户的css主题。然后使用profile分别定义这些Maven属性的值,如下所示。
<profiles>
<profile>
<id>client-a</id>
<properties>
<client.logo>a.jpg</client.logo>
<client.theme>red</client.theme>
</properties>
</profile>
<profile>
<id>client-b</id>
<properties>
<client.logo>b.jpg</client.logo>
<client.theme>blue</client.theme>
</properties>
</profile>
</profiles>
最后需要配置maven-war-plugin对src/main/webapp/这一web资源目录开启过滤,如下所示。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-beta-1</version>
<configuration>
<webResources>
<resource>
<filtering>true</filtering>
<directory>src/main/webapp</directory>
<includes>
<include>**/*.css</include>
<include>**/*.js</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
上面中声明了web资源目录src/main/webapp(也就是默认的web资源目录),然后配置filtering开启过滤,并且使用includes指定要过滤的文件,这里是所有css和js文件。
注意:可以模仿上述配置添加额外的web资源目录,选择是否开启过滤,以及包含或者排除一些该目录下的文件。
配置完成后,可以选择激活某个profile进行构建,如mvn clean install -Pclient -a,告诉web资源文件使用logo图片a.jpg,使用css主题red。