To be able to retrieve and store details of a todo, we need a Todo bean and a service to retrieve and store the details.
Let's create a Todo Bean:
public class Todo {
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo() {}
public Todo(int id, String user, String desc,
Date targetDate, boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
//ALL Getters
}
We have a created a simple Todo bean with the ID, the name of user, the description of the todo, the todo target date, and an indicator for the completion status. We added a constructor and getters for all fields.
Let's add TodoService now:
@Service
public class TodoService {
private static List<Todo> todos = new ArrayList<Todo>();
private static int todoCount = 3;
static {
todos.add(new Todo(1, "Jack", "Learn Spring MVC",
new Date(), false));
todos.add(new Todo(2, "Jack", "Learn Struts", new Date(),
false));
todos.add(new Todo(3, "Jill", "Learn Hibernate", new Date(),
false));
}
public List<Todo> retrieveTodos(String user) {
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if (todo.getUser().equals(user))
filteredTodos.add(todo);
}
return filteredTodos;
}
public Todo addTodo(String name, String desc,
Date targetDate, boolean isDone) {
Todo todo = new Todo(++todoCount, name, desc, targetDate,
isDone);
todos.add(todo);
return todo;
}
public Todo retrieveTodo(int id) {
for (Todo todo : todos) {
if (todo.getId() == id)
return todo;
}
return null;
}
}
Quick things to note are as follows:
- To keep things simple, this service does not talk to the database. It maintains an in-memory array list of todos. This list is initialized using a static initializer.
- We are exposing a couple of simple retrieve methods and a method to add a to-do.
Now that we have the service and bean ready, we can create our first service to retrieve a list of to-do's for a user.