org.beast.project.template.web.HomeController.java Source code

Java tutorial

Introduction

Here is the source code for org.beast.project.template.web.HomeController.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 org.beast.project.template.web;

import java.util.List;
import org.beast.project.template.hibernate.entities.Person;
import org.beast.project.template.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author u329022
 */
@Controller
public class HomeController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/index")
    public String home() {
        return "index";
    }

    @RequestMapping(value = "/result", method = RequestMethod.POST)
    public String processForm(@RequestParam("fName") String fName, @RequestParam("lName") String lName) {
        Person p = new Person();
        p.setFirstName(fName);
        p.setLastName(lName);
        personService.add(p);
        return "result";
    }

    @RequestMapping(value = "/display", method = RequestMethod.GET)
    public ModelAndView display() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("display");
        List<Person> persons = personService.getAll();
        mv.addObject("persons", persons);
        return mv;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ModelAndView delete(@RequestParam("id") String id) {
        System.out.println("ID :: " + id);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("display");
        long personId = Long.parseLong(id);
        personService.delete(personId);
        List<Person> persons = personService.getAll();
        mv.addObject("persons", persons);
        return mv;
    }
}