Thymeleaf GET表单绑定GetMapping控制器出现404错误求助
Hey there, let's break down what's causing that 404 error and get your search functionality working correctly!
The Core Problem
Your @GetMapping annotation is misconfigured. In Spring MVC, the value attribute defines the path of the endpoint, not including query parameters (the part after ?). When you wrote @GetMapping(value = "/SearchTerminal?code={code}"), Spring interprets the entire string as the literal path it needs to match—so it's looking for requests to http://localhost:8081/SearchTerminal?code={code} (with {code} as part of the path), not requests to /SearchTerminal with a code query parameter. That's why it throws the "No mapping for GET /SearchTerminal" error when you submit your form.
The Fix
You need to separate the path from the query parameter. Here's how to correct your controller code:
@GetMapping("/SearchTerminal") public String searchTerminal(@RequestParam("code") String code) { // Your business logic here (e.g., fetch terminal by code) return "edit-terminal"; }
Let's break this down:
@GetMapping("/SearchTerminal")tells Spring to handle GET requests to the/SearchTerminalpath.@RequestParam("code") String codetells Spring to extract thecodequery parameter from the URL (the?code=10101010part) and pass it to the method.
Why Your Form Is Already Correct
Your Thymeleaf form is set up properly:
<form action="/SearchTerminal" method="get" > <label for="code">label</label> <input type="number" id="code" name="code" class="form-control" /> <button type="submit" class="btn btn-primary btn-block ">Search</button> </form>
When you submit it, it generates the correct URL: http://localhost:8081/SearchTerminal?code=10101010—which now matches the corrected controller mapping.
Quick Note on API Design
Great call sticking with GET for this operation! Since you're retrieving data (not creating/modifying resources), GET is the right choice per REST principles. No need to switch to POST here—your approach aligns with best practices.
Bonus: Optional Parameters (If Needed)
If you ever want to make the code parameter optional (e.g., allow searching without a code), you can adjust the @RequestParam like this:
@RequestParam(value = "code", required = false) String code
This way, the method will still be called even if the code parameter isn't present in the URL.
内容的提问来源于stack exchange,提问作者Morteza

