Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 29, 2019 23:10
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/bff0d621624d2711bffb812fe7ce5b80 to your computer and use it in GitHub Desktop.
Save parzibyte/bff0d621624d2711bffb812fe7ce5b80 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.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