Skip to content

Commit 6b769b1

Browse files
committed
Work on #56
1 parent 296c44d commit 6b769b1

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

_posts/2015-03-17-controller.md

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,38 +9,67 @@ order: 0
99
Another approach to handling a request and producing a response is using Controllers. After routing has determined what controller to use, an action method will be invoked.
1010
In Pippo, controllers are instances of [Controller]({{ site.codeurl }}/pippo-controller-parent/pippo-controller/src/main/java/ro/pippo/controller/Controller.java).
1111

12+
#### How to use
13+
1214
Defining a new controller is simple:
1315

1416
```java
17+
@Path("/contacts")
1518
public class ContactsController extends Controller {
1619

20+
@GET("/?")
1721
public void index() {
1822
List<Contact> contacts = contactService.getContacts();
1923
getResponse().bind("contacts", contacts).render("contacts");
2024
}
2125

22-
public void getContact(@Param("id") int id) {
26+
@GET("/{id: [0-9]+}")
27+
public void getContact(@Param int id) {
2328
Contact contact = contactService.getContact(id);
2429
getResponse().bind("contact", contact).render(contact);
2530
}
2631

32+
@GET("/text")
33+
@Named("text")
34+
@Produces(Produces.TEXT)
35+
@NoCache
36+
public void complex(@Param int id, @Param String action, @Header String host, @Session String user) {
37+
// do something
38+
}
39+
2740
}
2841
```
2942

3043
Methods attached to the controller (for example `index` from above snippet) are known as action methods. When Pippo receives a request, it will create a new instance of the controller and call the appropriate action method.
3144
You can register a controller's action in application with a simple line:
3245

46+
```java
47+
public class MyApplication extends ControllerApplication {
48+
49+
@Override
50+
protected void onInit() {
51+
// add controller(s)
52+
addControllers(ContactsController.class); // one instance for EACH request
53+
// or
54+
addControllers(new ContactsController()); // one instance for ALL requests
55+
}
56+
57+
}
58+
```
59+
3360
```java
3461
public class ControllerDemo {
3562

3663
public static void main(String[] args) {
37-
Pippo pippo = new Pippo();
38-
pippo.GET("/", ContactsController.class, "index");
39-
pippo.GET("/contact/{id}", ContactsController.class, "getContact");
64+
Pippo pippo = new Pippo(new MyApplication());
4065
pippo.start();
4166
}
4267

4368
}
4469
```
4570

71+
#### Implementation details
72+
73+
Advanced features (Extractor, Interceptor, ...) and technical aspects are presented in details [here](https://github.com/decebals/pippo/pull/341).
74+
4675
You can see a demo [here]({{ site.demourl }}/pippo-demo-controller)

0 commit comments

Comments
 (0)