|
| 1 | +package com.ecars.microcars.controller; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +import com.ecars.microcars.form.CarForm; |
| 7 | +import com.ecars.microcars.model.Car; |
| 8 | +import org.springframework.beans.factory.annotation.Value; |
| 9 | +import org.springframework.stereotype.Controller; |
| 10 | +import org.springframework.ui.Model; |
| 11 | +import org.springframework.web.bind.annotation.ModelAttribute; |
| 12 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 13 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 14 | + |
| 15 | +@Controller |
| 16 | +public class MainController { |
| 17 | + |
| 18 | + private static List<Car> cars = new ArrayList<Car>(); |
| 19 | + |
| 20 | + static { |
| 21 | + cars.add(new Car ("Honda", "Jazz")); |
| 22 | + cars.add(new Car ("Volvo", "940")); |
| 23 | + cars.add(new Car( "Opel", "Corsa")); |
| 24 | + } |
| 25 | + |
| 26 | + // Injectez (inject) via application.properties. |
| 27 | + @Value("${welcome.message}") |
| 28 | + private String message; |
| 29 | + |
| 30 | + @Value("${error.message}") |
| 31 | + private String errorMessage; |
| 32 | + |
| 33 | + @RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET) |
| 34 | + public String index(Model model) { |
| 35 | + |
| 36 | + model.addAttribute("message", message); |
| 37 | + |
| 38 | + return "index"; |
| 39 | + } |
| 40 | + |
| 41 | + @RequestMapping(value = { "/carList" }, method = RequestMethod.GET) |
| 42 | + public String carList(Model model) { |
| 43 | + |
| 44 | + model.addAttribute("cars", cars); |
| 45 | + |
| 46 | + return "carList"; |
| 47 | + } |
| 48 | + |
| 49 | + @RequestMapping(value = { "/addCar" }, method = RequestMethod.GET) |
| 50 | + public String showAddCarPage(Model model) { |
| 51 | + |
| 52 | + CarForm carForm = new CarForm(); |
| 53 | + model.addAttribute("carForm", carForm); |
| 54 | + |
| 55 | + return "addCar"; |
| 56 | + } |
| 57 | + |
| 58 | + @RequestMapping(value = { "/addCar" }, method = RequestMethod.POST) |
| 59 | + public String saveCar(Model model, // |
| 60 | + @ModelAttribute("carForm") CarForm carForm) { |
| 61 | + |
| 62 | + String brand = carForm.getBrand(); |
| 63 | + String modele = carForm.getModele(); |
| 64 | + |
| 65 | + if (brand != null && brand.length() > 0 // |
| 66 | + && modele != null && modele.length() > 0) { |
| 67 | + Car newCar = new Car(brand, modele); |
| 68 | + cars.add(newCar); |
| 69 | + |
| 70 | + return "redirect:/carList"; |
| 71 | + } |
| 72 | + |
| 73 | + model.addAttribute("errorMessage", errorMessage); |
| 74 | + return "addCar"; |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments