在 Thymeleaf 的同一页面上显示输入参数

Showing input parameter on same page in Thymeleaf

我试图在与 Thymleaf 和 Spring 中的表单相同的页面上显示结果,这是我迄今为止尝试过的方法:

控制器:

   @Controller
public class ThymeleafController {
    
    @GetMapping("/hello")
    public String getHello() {
        return "hello";
    }
    
    
    @PostMapping("/test")
    public String test(@RequestParam("text1")String str, Model model) {
        
        model.addAttribute("sample", str);
        
        return "test";
    }
    
}

test.html 页数:

    <!DOCTYPE html>
<html xmlns:th ="http://www.thymeleaf.org" >
<head>
<meta charset ="UTF-8" ></meta>
<title> Hello World</title>
</head>
<body>
<h1> Hello World</h1>
<form method ="post" action ="/test" >
Enter: <input type ="text" name ="text1" />
<input type ="submit" value ="click" />
</form>
<span th:text ="${sample == null} ? 'null' : ${sample}" ></span>
</body>
</html>

当我进入测试页面时,我看到了这个错误:

  There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

谁能给我一个想法或一个例子,告诉我如何在与表单/输入相同的页面上显示一个值?谢谢

参考:https://hellokoding.com/handling-form-submission-example-with-java-spring-boot-and-freemarker/

添加get,这样问题就解决了。

@Controller
public class ThymeleafController {
    
    @GetMapping("/hello")
    public String getHello() {
        return "hello";
    }
    
    @GetMapping("/test")
    public String testfrm() {
        return "test";
    }

    @PostMapping("/test")
    public String test(@RequestParam("text1")String str, Model model) {
        
        return "test";
    }
    
}