Search code examples
springpostthymeleaf

I can not make friends Thymeleaf and Spring


when you click the search button an error occurs in my html:

<form method="post"> <input type="number" name="numberProt"> <button type="submit">Найти</button> </form>

in my @Controller

@Controller
public class ViolationController {
    @Autowired
    private ViolationServiceImpl violationService;

    @GetMapping("/violations")
    public String viewViolations(Model model) {
        List<Violation> listViolations = violationService.findAll();
        model.addAttribute("listViolations", listViolations);

        return "violations";
    }

    @PostMapping("filterProt")
    public String filterViolation(Integer numberProt, Model model) {
        Iterable<Violation> protocols;
        if (numberProt != null) {
            protocols = violationService.findByNumProtocol(numberProt);
        } else {
            protocols = violationService.findAll();
        }
        model.addAttribute(protocols);
        return "/violations";
    }
}

I ask you to help. An error occurs: Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]


Solution

  • Your form is not correct, it has no action. Simply correct your form to this:

    <form action="/filterProt" method="post">
       <input type="number" name="numberProt">
       <button type="submit">Найти</button>
    </form>
    

    Additionally, your controller handler lacks @ModelAttribute annotation:

    @PostMapping("filterProt")
    public String filterViolation(@ModelAttribute NumberModel numberModel, Model model) {
    ....
    }
    

    Where NumberModel is:

    public class NumberModel{
        private Integer numberProt;
    
        public Integer getNumberProt() {
            return numberProt;
        }
    
        public void setNumberProt(Integer numberProt) {
            return this.numberProt = numberProt;
        }
    }