Search code examples
mavenjettymaven-jetty-plugin

How do I change the working directory while running Jetty with Maven?


I'm running a Jetty server using Maven by executing the mvn jetty:run goal. In my Java code, I read files using java.io.File, but my existing code assumes that the process is running in the /war directory under my basedir.

How do I set the working directory when using the Maven Jetty plugin?

Details: Those files are not directly under the baseDirectory but under a child directory: specifically, the webapp directory, which is copied to the target folder under ${project.artifactId}-${project.version}

I want to read the files without having to add the target path every time I define a file.

I can read files using.

File file = new File("target/myProject-myVersion/fileToRead.txt")

I just want to do:

File file = new File("fileToRead.txt")

Below is the project structure. (It's the typical Maven webapp structure.)

MyDir/
  [pom.xml]
  src/main/
    java/
      com.example.mycode/
        MyCode.java
    webapp/
      [fileToRead.txt]
      [index.html]
      [jsp.jsp]
      WEB-INF/
        [web.xml]

In pom.xml I have:

             <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.3.7.v20160115</version>
                <configuration>
                    <webAppSourceDirectory>${project.basedir}/target/${project.artifactId}-${project.version}</webAppSourceDirectory>
                </configuration>
            </plugin>

Solution

  • Use the ServletContext.getRealPath(String) API.

    File file = new File(servletContext.getRealPath("/fileToRead.txt"));