vn.edu.vnuk.tasks_jpa.controller.TasksController.java Source code

Java tutorial

Introduction

Here is the source code for vn.edu.vnuk.tasks_jpa.controller.TasksController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.vnuk.tasks_jpa.controller;

import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import vn.edu.vnuk.tasks_jpa.dao.TaskDao;
import vn.edu.vnuk.tasks_jpa.model.Task;

/**
 *
 * @author michel
 */
@Controller
public class TasksController {

    private TaskDao dao;

    @Autowired
    public TasksController(TaskDao dao) {
        this.dao = dao;
    }

    @RequestMapping("addTask")
    public String add() {
        return "task/add";
    }

    @RequestMapping("createTask")
    public String create(@Valid Task task, BindingResult result) throws SQLException {

        if (result.hasFieldErrors("description")) {
            return "task/add";
        }

        dao.create(task);
        return "task/added";
    }

    @RequestMapping(value = { "", "/", "tasks" })
    public String read(Model model) throws SQLException {
        model.addAttribute("tasks", dao.read());
        return "task/index";
    }

    @RequestMapping("editTask")
    public String edit(@RequestParam Map<String, String> taskId, Model model) throws SQLException {
        Long id = Long.parseLong(taskId.get("id").toString());
        model.addAttribute("task", dao.read(id));
        System.out.println(
                "vn.edu.vnuk.tasks_jpa.controller.TasksController.edit() : " + dao.read(id).getDescription());
        return "task/edit";
    }

    @RequestMapping("updateTask")
    public String update(@Valid Task task, BindingResult result) throws SQLException {

        if (result.hasFieldErrors("description")) {
            return "task/edit";
        }

        dao.update(task);
        return "task/updated";
    }

    @RequestMapping(value = "deleteTask", method = RequestMethod.POST)
    public void delete(Long id, HttpServletResponse response) throws SQLException {
        dao.delete(id);
        response.setStatus(200);
    }

    @RequestMapping(value = "completeTask", method = RequestMethod.POST)
    public void complete(Long id, HttpServletResponse response) throws SQLException {
        dao.complete(id);
        response.setStatus(200);
    }

}