Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 27, 2019 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/88f06ce1a477972e6bea5e7bc54fd9e0 to your computer and use it in GitHub Desktop.
Save parzibyte/88f06ce1a477972e6bea5e7bc54fd9e0 to your computer and use it in GitHub Desktop.
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@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 Producto producto, RedirectAttributes redirectAttrs) {
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