Java tutorial
/* * 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 ash.resourcemanager.spring.controllers; import ash.resourcemanager.hibernate.GenericDAO; import ash.resourcemanager.hibernate.pojo.Customer; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; /** * * @author Ash */ @Controller @SessionAttributes public class CustomersController { private GenericDAO<Customer> _customersDAO; @RequestMapping(value = "/customers", method = RequestMethod.GET) public ModelAndView showCustomers() { List<Customer> customers = getDAO().getAll(); ModelAndView modelAndView = new ModelAndView("customers"); modelAndView.addObject("list", customers); return modelAndView; } @RequestMapping(value = "/customerForm") public ModelAndView showCustomerForm(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("customerForm"); String method = request.getParameter("action"); if (method.equals("add")) { modelAndView.addObject("command", new Customer()); } else if (method.equals("edit")) { String customerId = request.getParameter("id"); Customer customer = getDAO().getById(Integer.parseInt(customerId)); modelAndView.addObject("command", customer); } return modelAndView; } @RequestMapping(value = "/saveCustomer", method = RequestMethod.POST) public String saveCustomer(@ModelAttribute("customer") Customer customer, BindingResult result) { System.out.println("customer id:" + customer.getCustomerId() + "name" + customer.getName()); if (customer.getCustomerId() == null) { getDAO().create(customer); } else { Customer customerObject = getDAO().getById(customer.getCustomerId()); customerObject.setName(customer.getName()); getDAO().update(customerObject); } return "redirect:customers.htm"; } @RequestMapping(value = "/deleteCustomer") public String deleteCustomer(HttpServletRequest request) { GenericDAO<Customer> dao = getDAO(); String customerId = request.getParameter("id"); Customer customer = dao.getById(Integer.parseInt(customerId)); dao.delete(customer); return "redirect:customers.htm"; } public GenericDAO<Customer> getDAO() { if (_customersDAO == null) { _customersDAO = new GenericDAO(Customer.class); } return _customersDAO; } }