Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packaging Javascript files in a war?

I am developing a Servlet based Java project which is to be packaged as a war using Maven. Is there a way I can include JavaScript (JS) files along with this project (they should be available at some url when the project loads on a Tomcat Server).

I have looked around but have not found any working solutions.

like image 476
sheki Avatar asked Oct 08 '10 13:10

sheki


3 Answers

Maybe the better solution is to stick to Maven convention, which specifies that the root directory of your Web application is src/main/webapp.

So if you put all your Javascript files in src/main/webapp/javascript (or src/main/webapp/js), they will be integrated in your final war package.

In the Maven WAR plugin, they give some descriptions (see here for example) about the content of the directories. For example:

 |-- pom.xml
 `-- src
     `-- main
         |-- java
         |   `-- com
         |       `-- example
         |           `-- projects
         |               `-- SampleAction.java
         |-- resources
         |   `-- images
         |       `-- sampleimage.jpg
         `-- webapp
             |-- WEB-INF
             |   `-- web.xml
             |-- index.jsp
             `-- jsp
                 `-- websource.jsp

As you can see, you can put resources in webapp/xxx directory, such as jsp file here.

As stated by cuh, you can also configure the Maven WAR plugin if your directory structure is different.

like image 132
Romain Linsolas Avatar answered Sep 22 '22 20:09

Romain Linsolas


You can use the maven-war-plugin and configure it something like this:

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-war-plugin</artifactId>
       <version>2.0.2</version>
       <configuration>
           <warSourceDirectory>${basedir}/src/main/webapp</warSourceDirectory>
           <webResources>
                <resource>
                    <directory>your/path/to/js</directory>
                    <targetPath>js</targetPath>
                </resource>
           </webResources>
       </configuration>
</plugin>

See here.

edit: You probably don't want to include the js into the classes Folder.

like image 41
cuh Avatar answered Sep 24 '22 20:09

cuh


Put them in directories under src/main/webapp. That is, assuming you generated it using the maven-archetype-webapp archetype.

My current app has them under src/main/webapp/javascript, and accesses them in JSPs like this:

<script type="text/javascript" src="javascript/jquery-1.4.2.min.js"></script>

(for jsp files in src/main/webapp that is)

like image 31
Powerlord Avatar answered Sep 22 '22 20:09

Powerlord