You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf GET表单绑定GetMapping控制器出现404错误求助

Fixing Your GET Request Mapping Issue in Spring MVC + Thymeleaf

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 /SearchTerminal path.
  • @RequestParam("code") String code tells Spring to extract the code query parameter from the URL (the ?code=10101010 part) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:02:53