This guide will get you started using Spark on Heroku/Cedar. Spark is basically a clone of Sinatra for Java. 'Nuff said.
Create a single Java main class in src/main/java/HelloWorld.java
:
:::java
import static spark.Spark.*;
import spark.*;
public class HelloWorld {
public static void main(String[] args) {
setPort(Integer.parseInt(System.getEnv("PORT"));
get(new Route("/hello") {
@Override
public Object handle(Request request, Response response) {
return "Hello World!";
}
});
}
}
Set up your pom.xml
:
:::xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
<artifactId>mysparkapp</artifactId>
<repositories>
<repository>
<id>Spark repository</id>
<url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>spark</groupId>
<artifactId>spark</artifactId>
<version>0.9.9.3-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>copy-dependencies</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Put the launch command in a file called Procfile
:
web: java -cp "target/dependency/*":target/classes HelloWorld
Add a .gitignore
to prevent generated files from being checked in:
$ echo target > .gitignore
Create a git repo and check in your code
$ git init
$ git add .
$ git commit -m init
Create an app on the Cedar stack:
$ heroku create --stack cedar
$ git push heroku master
Counting objects: 9, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (9/9), 1.16 KiB, done.
Total 9 (delta 0), reused 0 (delta 0)
-----> Heroku receiving push
-----> Java app detected
-----> Installing Maven 3.0.3..... done
-----> Installing settings.xml..... done
-----> executing .maven/bin/mvn -B -Duser.home=/tmp/build_brdc75hmaxsu -s .m2/settings.xml -DskipTests=true clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building hellospark 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
-----> Discovering process types
Procfile declares types -> web
-----> Compiled slug size is 14.2MB
-----> Launching... done, v3
http://cold-moon-3783.herokuapp.com deployed to Heroku
Test that it works:
$ curl http://cold-moon-3783.herokuapp.com/hello
Hello World!
i have the same question as shufenghui, how you got the static files working?