Created
August 29, 2019 23:10
-
-
Save parzibyte/bff0d621624d2711bffb812fe7ce5b80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hello; | |
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.*; | |
import org.springframework.web.servlet.mvc.support.RedirectAttributes; | |
import javax.validation.Valid; | |
@Controller | |
@RequestMapping(path = "/productos") | |
public class ProductosController { | |
@Autowired | |
private ProductosRepository productosRepository; | |
@GetMapping(value = "/agregar") | |
public String agregarProducto(Model model) { | |
model.addAttribute("producto", new Producto()); | |
return "productos/agregar_producto"; | |
} | |
@GetMapping(value = "/mostrar") | |
public String mostrarProductos(Model model) { | |
model.addAttribute("productos", productosRepository.findAll()); | |
return "productos/ver_productos"; | |
} | |
@PostMapping(value = "/eliminar") | |
public String eliminarProducto(@ModelAttribute Producto producto, RedirectAttributes redirectAttrs) { | |
redirectAttrs | |
.addFlashAttribute("mensaje", "Eliminado correctamente") | |
.addFlashAttribute("clase", "warning"); | |
productosRepository.deleteById(producto.getId()); | |
return "redirect:/productos/mostrar"; | |
} | |
@PostMapping(value = "/editar") | |
public String actualizarProducto(@ModelAttribute Producto producto, RedirectAttributes redirectAttrs) { | |
productosRepository.save(producto); | |
redirectAttrs | |
.addFlashAttribute("mensaje", "Editado correctamente") | |
.addFlashAttribute("clase", "success"); | |
return "redirect:/productos/mostrar"; | |
} | |
@GetMapping(value = "/editar/{id}") | |
public String mostrarFormularioEditar(@PathVariable int id, Model model) { | |
model.addAttribute("producto", productosRepository.findById(id)); | |
return "productos/editar_producto"; | |
} | |
@PostMapping(value = "/agregar") | |
public String guardarProducto(@ModelAttribute @Valid Producto producto, BindingResult bindingResult, RedirectAttributes redirectAttrs) { | |
if (bindingResult.hasErrors()) { | |
return "productos/agregar_producto"; | |
} | |
productosRepository.save(producto); | |
redirectAttrs | |
.addFlashAttribute("mensaje", "Agregado correctamente") | |
.addFlashAttribute("clase", "success"); | |
return "redirect:/productos/mostrar"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment