TecnologiaController.java 2.54 KB
Newer Older
1 2 3 4 5
package com.roshka.controller;

import com.roshka.modelo.Tecnologia;
import com.roshka.repositorio.TecnologiaRepository;
import org.springframework.beans.factory.annotation.Autowired;
6 7 8 9
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
10 11 12 13 14 15
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
16 17

@Controller
18
@RequestMapping("/tecnologias")
19 20 21 22 23 24 25 26 27 28 29
public class TecnologiaController {
 
    TecnologiaRepository tecRepo;


@Autowired 
public TecnologiaController(TecnologiaRepository tecRepo){
   this.tecRepo = tecRepo;

}

30
@GetMapping(path = {"/agregar","/modificar/{id}"})
31 32 33 34 35
public String addtecnologiaView(Model model,@PathVariable(required = false) Long id) {
    
    
    if(id == null) model.addAttribute("tecnologia", new Tecnologia());
    else model.addAttribute("tecnologia", tecRepo.getById(id));
36 37
    return "tecnologia-form";
}
38

39
@RequestMapping()
40
    public String menuTecnologias(Model model,@RequestParam(required = false) String nombre,@RequestParam(defaultValue = "0")Integer nroPagina) {
41
        final Integer CANTIDAD_POR_PAGINA = 10;
42
        Pageable page = PageRequest.of(nroPagina,CANTIDAD_POR_PAGINA,Sort.by("id"));
43 44 45 46 47 48 49
        
        if(nombre == null || nombre.trim().isEmpty()) {
            Page<Tecnologia> tecnologiaPag=tecRepo.findAllTecnologia(page);
            model.addAttribute("tecnologias", tecnologiaPag.getContent());
            model.addAttribute("pages", tecnologiaPag.getTotalPages());
        }
        else {
50
            Page<Tecnologia> tecnologiaPag=tecRepo.findByNombreContainingIgnoreCase(nombre.trim(),page);    
51 52 53
            model.addAttribute("pages", tecnologiaPag.getTotalPages());
            model.addAttribute("tecnologias", tecnologiaPag.getContent());
        }
54 55 56
        return "tecnologias";
    }

57
@PostMapping(path = {"/agregar","/modificar/{id}"})
58 59 60 61 62
    public String addtecnologia(@Valid @ModelAttribute Tecnologia tecnologia, BindingResult result, @PathVariable(required = false) Long id, Model model) {
        if(result.hasErrors() || (id==null && tecRepo.existsByNombreIgnoreCase(tecnologia.getNombre()))){
            model.addAttribute("mismoNombre", true);
            return "tecnologia-form";
        } 
63 64
        if(id != null ) tecnologia.setId(id);
        tecRepo.save(tecnologia);
65
        return "redirect:/tecnologias";
66 67 68 69 70 71
    } 




}