Your first Controller - geetools/geemvc GitHub Wiki
The controller in MV**[C]** is a class that controls the flow of a particuar action and connects the model with the view. A controller itself should ideally not have any view logic or execute complex business logic - the latter should preferrably be taken care of by some service layer. In most cases the view ought to be in an external file, as we will see later.
A geeMVC controller is a class containing handler methods that are mapped to specific requests. A handler-method is basically a simple none-static method within a controller that runs arbitrary code. What makes the method special is that you do not have to call it manually or programmatically yourself, but instead it is mapped to a request URL. For example: in our hello-world webapp we tell geeMVC that when someone enters the URL http://localhost:8080/hello/world into their browser, we want our handler method sayHello() to be executed. geeMVC takes care of this for you.
Normally of course you would not simply say "hello". A typical use-case would be to retrieve data from the database and show some information to the user, or to save the data that was sent from a HTML form into a database.
Now lets dive straight into a concrete example. Check out the code:
HelloWorld.java
package com.example;
import com.geemvc.annotation.Controller;
import com.geemvc.annotation.Request;
@Controller
public class HelloWorld {
@Request("/hello/world")
public String sayHello() {
return "view: hello-world";
}
}
In your Java-IDE it should look something like this:
We have simply created a new java class, annotated it with @Controller and implemented our first handler method sayHello(). So that geeMVC knows when to call this method, we have also annotated it with @Request and mapped it to the URI "/hello/world".
In this example our method-handler is returning a string, which tells geeMVC two things:
- Please forward the request to my view.
- Please take the user to my JSP page "hello-world.jsp" (more on that in the next section).
Now that we have created our first controller, lets tell geeMVC what to send back to the user. For that take a look at the next step Your first JSP Page.
If you are new to eclipse and do not know how to create a class, have a look here.