{#========================================== Demos - Hello World ==========================================#} {% extends "../demos.html" %} {% block subSectionClasses %}demo_hello_world{% endblock %} {% block meta_title %}Demo - Hello World!{% endblock %} {% block meta_description %}"Hello World!" demo and tutorial using Spincast{% endblock %} {% block subBody %}
In this tutorial, we're going to present two "Hello World!" versions:
First, you add the latest version of the org.spincast:spincast-default
Maven artifact to your pom.xml (or build.gradle):
<dependency>
<groupId>org.spincast</groupId>
<artifactId>spincast-default</artifactId>
<version>{{spincast.spincastCurrrentVersion}}</version>
</dependency>
Then you bootstrap everything using a main(...) method :
public class App {
public static void main(String[] args) {
Injector guice = Guice.createInjector(new SpincastDefaultGuiceModule(args));
DefaultRouter router = guice.getInstance(DefaultRouter.class);
router.GET("/").save(context -> context.response().sendPlainText("Hello World!"));
guice.getInstance(Server.class).start();
}
}
Explanation :
(Tip : try hovering/clicking the page numbers below!)
main(...) method! This
is the entry point of a standard Spincast application.
SpincastDefaultGuiceModule module. This module binds a default
implementation for all the required components of a Spincast application.
DefaultRouter) from Guice.
GET Route for the
"/" index page, using a Java 8's lambdas syntax.
This inline route handler sends a plain text "Hello World!" message to the user.
Server) from Guice and
we start it!
Now, if you would point your browser to http://localhost:44419
(Spincast default port is 44419), you should see the
"Hello World!" message.
Here's the exact same example but using Java 7, so without lambdas. We prefer this version
for a first example because the types of the various components are more obvious!:
public class App {
public static void main(String[] args) {
Injector guice = Guice.createInjector(new SpincastDefaultGuiceModule(args));
DefaultRouter router = guice.getInstance(DefaultRouter.class);
router.GET("/").save(new DefaultHandler() {
@Override
public void handle(DefaultRequestContext context) {
context.response().sendPlainText("Hello World!");
}
});
guice.getInstance(Server.class).start();
}
}
Explanation :
save(...) method in fact takes a Route Handler as a parameter.
In this simple example, the Route Handler is declared inline using the
DefaultHandler interface. We'll learn more about route handlers in the
next example.
We're not big fans of those very short "Hello world!" examples because, in real life, you usually don't develop such basic applications. You want an architecture that is flexible and scalable! So, let's use a more flexible structure now.
In this second example we'll:
App class itself being managed by Guice.
Request Context type.
If you look carefully, in the previous example we used a lot of Default components
("DefaultRouter" for example).
Those Default components are useful to have a quick up and running Spincast application.
But they hide the fact that they
represent objects that are actually parameterized. In Spincast, most of the components related to
the routing process are parameterized with the Request Context type. You can learn more about
this topic in the The Request Context
section of the documentation, but we'll introduce it briefly here.
A Request Context is the object Spincast passes to the matching Route Handlers
when a request arrives. This object allows your handlers to access information
about the current request (its body, headers, path parameters, etc.) and
to build the response that is going to be sent back (its body, headers, http status, etc.).
But there are also more generic utility methods on the Request Context, methods not directly
related to the request or the response. Here's a quick example :
{% verbatim %}
public void myHandler(DefaultRequestContext context) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", "Stromgol");
String result = context.templating().evaluate("Hello {{name}}", params);
// Do something with the result...
}{% endverbatim %}
Explanation :
templating() "method"
is not directly related to the request or the response.
It's an add-on that provides utilities to the
Route Handlers.
In our first "Hello World" example, the request context type was DefaultRequestContext,
which is the default.
In Spincast, this default type can be extended, you can add extra
functionalities to it! Those functionalities can be simple methods or full objects,
called add-ons. Most of the time, those add-ons are provided by
plugins.
But why would we want to extend the Request Context in the first place?
Imagine a plugin
which job is to manage authentification and autorization. Wouldn't it be nice if
this plugin could add some extra functionalities to the Request Context?
For example :
router.GET("/").save(new DefaultHandler() {
@Override
public void handle(DefaultRequestContext context) {
if(context.auth().isAuthenticated()) {
String username = context.auth().user().getUsername();
// ...
}
}
});
This is what being able to extend the Request Context allows.
So in this new and improved "Hello world!" example, we're going to use a custom
Request Context type: AppRequestContext. We're going to add a simple method
to it : translate(String sentence, Locale from, Locale to),
which job will be to translate a sentence from one language to another. By adding this
new method to our custom Request Context type, our Route Handlers will have
easy access to it.
Note that, for this second example, we still have to include the org.spincast:spincast-default
Maven artifact because, even if we'll use a custom Request Context type, we'll still be
using all the other default components (the default HTTP Server, for example).
Let's first have a look at what our new App class will be. We'll create the other
required components after.
public class App {
public static void main(String[] args) {
Injector guice = Guice.createInjector(new AppModule());
App app = guice.getInstance(App.class);
app.start();
}
private final Server server;
private final Router<AppRequestContext, DefaultWebsocketContext> router;
@Inject
public App(Server server, Router<AppRequestContext, DefaultWebsocketContext> router) {
this.server = server;
this.router = router;
}
public void start() {
this.router.GET("/").save(new Handler<AppRequestContext>() {
@Override
public void handle(AppRequestContext context) {
String translated = context.translate("Hello World!",
Locale.ENGLISH,
Locale.FRENCH);
context.response().sendPlainText(translated);
}
});
this.server.start();
}
}
Explanation :
App class is still the
entry point of our application but, in this new example, it is also going to
be part of the Guice context!
SpincastDefaultGuiceModule Guice module provided by Spincast, we
use a custom Guice module, AppModule (listed below).
App instance and we call its start() method.
As you'll see, we'll bind the App class itself in our
custom AppModule module, so Guice manages it!
App instance is
managed by Guice, all the required dependencies will be automatically injected
in its constructor. Here, we inject the HTTP Server and
a custom and parameterized Router :
Router<AppRequestContext, DefaultWebsocketContext>.
We'll see that because the Router is parameterized with a custom
Request Context type, "AppRequestContext", our Route Handlers will
have access to a new translate(...) method... You can see that the Router is also
parameterized with a Websocket context type, but that's not important in this example.
start() method called
at line 8, once the
Guice context is created.
GET Route for the "/" endpoint.
Here, we won't use Java 8 lambdas or method handles so you can clearly see
the types involved. Since the Router,
Router<AppRequestContext, DefaultWebsocketContext>,
is parameterized with our custom
Request Context type, the handler type,
Handler<AppRequestContext>, will also be.
handle(...) method receives an
instance of our
custom Request Context type, "AppRequestContext".
translate(...) method, available directly on the Request Context
object!
Now that we looked at the new App class, let's create our custom AppRequestContext
type in which the new translate(...) method will be defined :
public interface AppRequestContext extends RequestContext<AppRequestContext> {
public String translate(String sentence, Locale from, Locale to);
// Other custom methods and/or add-ons...
}
Explanation :
Request Context interface
must extend the RequestContext base interface and parameterize it
using its own type. To learn more about this, check the
Extending the Request Context
section of the documentation.
translate(...) method.
Then, let's add an implementation for this interface :
public class AppRequestContextDefault extends RequestContextBase<AppRequestContext>
implements AppRequestContext {
@AssistedInject
public AppRequestContextDefault(@Assisted Object exchange,
RequestContextBaseDeps<AppRequestContext> requestContextBaseDeps) {
super(exchange, requestContextBaseDeps);
}
@Override
public String translate(String sentence, Locale from, Locale to) {
// Ok, it's more hardcoded than translated for now!
return "Salut, monde!";
}
}
Explanation :
RequestContextBase
class to keep all the functionalities of the default
Request Context, but also implements
our custom AppRequestContext interface, where our new
translate(...) method is declared.
@AssistedInject because it will be used by a Guice
assisted factory.
Don't worry too much about this or about the parameters,
they are simply required by the parent class's constructor.
translate(...).
Finally, we bind everything together by creating a custom
Guice module, AppModule. This module is the one
used by our App class to create the Guice context.
public class AppModule extends SpincastDefaultGuiceModule {
@Override
protected void configure() {
super.configure();
bind(App.class).in(Scopes.SINGLETON);
}
@Override
protected Class<? extends RequestContext<?>> getRequestContextImplementationClass() {
return AppRequestContextDefault.class;
}
}
Explanation :
SpincastDefaultGuiceModule since we want to keep the
default bindings and only tweak a few things.
configure()
method, we bind our App class itself! That way, Guice knows about it
and is able to inject the dependencies it requires.
getRequestContextImplementationClass() method to let Spincast know that
it has to use our custom
AppRequestContextDefault Request Context type instead of the default one!
Note that Spincast will automatically find the associated AppRequestContext
interface and will use it to parameterize the Router and the other routing
related components.
And that's it! If you start this application (using the main(...) method of
the App class) and point your browser to
http://localhost:44419, you'll see "Salut, monde!".
Extending the Request Context type may seem like a lot of code!
But once in place, adding new functionalities is pretty easy. And you'll have a solid and flexible
base to build your application.
That said, if it's too much, you can also start using Spincast with the provided default components and only switch to custom ones when you feel ready...
Note that if you use the Quick Start
application as a start, the customization of
the Request Context type has already been done for you.
Our second example was a good step forward. But in a real life application, your logic
wouldn't all be inside a single App class! You would have controllers,
services, respositories, etc.
Make sure you read the Bootstrapping your app section of the documentation for more ideas on how to structure a real life Spincast application.