Java Postmapping-为什么它在没有模型的情况下工作?

Java Postmapping-为什么它在没有模型的情况下工作?,java,spring,post,controller,thymeleaf,Java,Spring,Post,Controller,Thymeleaf,我最近开始学习Spring,我编写了一个非常简单的“应用程序”,以了解它如何处理get和post请求以及控制器。基本上,它所做的只是从输入文本中获取某种值,并对其进行处理,以确保我以后可以在程序中使用它 我的代码是: <form th:action="@{/main/form2}" th:method="post"> <input th:object="${postdata}" placeholder="Write it here..." name="postdata">

我最近开始学习Spring,我编写了一个非常简单的“应用程序”,以了解它如何处理get和post请求以及控制器。基本上,它所做的只是输入文本中获取某种,并对其进行处理,以确保我以后可以在程序中使用它

我的代码是:

<form th:action="@{/main/form2}" th:method="post">
<input th:object="${postdata}" placeholder="Write it here..." 
name="postdata">
<input type="submit" name="submit" value="submit">
我的问题如下:

  • 为什么它在没有从模型类实例化对象的情况下工作 是否向其添加此模型属性?我沟通时是否只需要一个模型 在另一个方向,当我从Spring向html发送一些值时 页面
  • 这样做合适吗

  • 提前谢谢。

    您所说的“如果我没有模型”是什么意思?谢谢您的提问。我的意思是从Model类实例化一个对象以向其添加ModelAttribute。好的,Spring将根据引入的属性自动为您构建一个
    Model
    实例。您可以将
    模型
    对象或其任何部分作为
    @modeldattribute
    注入。
    @RequestMapping("/main")
    public class Controller {
        @GetMapping("/form")
        public String getInfo() {
            return "form";
        }
    
        @PostMapping("/form2") //end point name
        public String postInfo(@ModelAttribute("postdata") String receivedData){
            System.out.println(receivedData);
    
            //ModelAttribute: what you get from the HTML.
            //It works, even if i do not have a model
    
            return "redirect:/main/form"; //HTML name
    
        }
    }