com.leapfrog.academyspring.controller.CourseController.java Source code

Java tutorial

Introduction

Here is the source code for com.leapfrog.academyspring.controller.CourseController.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 com.leapfrog.academyspring.controller;

import com.leapfrog.academyspring.entity.Course;
import com.leapfrog.academyspring.service.CourseService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Suman Heuju
 */
@Controller
@RequestMapping(value = { "/courses" })
public class CourseController {
    @Autowired
    CourseService courseService;

    @RequestMapping(method = RequestMethod.GET)
    public String courseDisplay(Model model) {
        courseService.getAll().clear();
        model.addAttribute("courses", courseService.getAll());
        return "course/courses";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView add() {
        ModelAndView mv = new ModelAndView("course/addcourse");
        mv.addObject("Course", new Course());
        return mv;
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("course/editcourse");
        mv.addObject("Course", courseService.getById(id));
        return mv;
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") int id) {
        courseService.delete(id);
        return "redirect:/courses";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute("Course") Course c) {
        if (c.getId() == 0) {
            courseService.insert(c);
        } else {
            courseService.update(c);
        }
        return "redirect:/courses";
    }

}