【问题标题】:Getting data by form and pass to controller通过表单获取数据并传递给控制器
【发布时间】:2019-11-01 18:45:27
【问题描述】:

我想将用户输入的 id 作为输入并传递给控制器​​以获取特定 id 的数据

当我在 URL 中手动传递 id 时它正在工作 -- http://localhost:8080/student/1


<form th:action="@{{student}/{id}}" th:object="${Student}" method="post">
                    Roll Number:<br>
                    <input type="text" th:field="*{id}"><br>
                    <br><br>
                    <input class="button" type="submit" value="Submit">
 </form>

@GetMapping(value = "/student/{id}")
    public Optional<Student> getStudentDetail(@PathVariable int id){
        return studentRepository.findById(id) ;
    }

白标错误页面 此应用程序没有显式映射 /error,因此您将其视为后备。

2019 年 6 月 19 日星期三 11:04:22 IST 出现意外错误(类型=内部服务器错误,状态=500)。 模板解析时出错(模板:“类路径资源[templates/student.html]”)

【问题讨论】:

    标签: spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    您应该使用th:field 代替&lt;input&gt;

    <input type="text" th:field="*{id}">
    

    【讨论】:

    • Whitelabel 错误页面 此应用程序没有明确的 /error 映射,因此您将其视为后备。 IST 2019 年 6 月 19 日星期三 11:27:55 出现意外错误(类型=内部服务器错误,状态=500)。执行处理器“org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor”时出错(模板:“student” - 第 16 行,第 40 列)
    • 通过使用
    【解决方案2】:

    AmirBll 所说,另外,您必须将控制器 HTTP 方法从 @GetMapping(value = "/student/{id}") 更改为 @PostMapping(value = "/student/{id}") form data 提交就是你在表单中声明的​​POST 方法。

    【讨论】:

      【解决方案3】:

      在表单属性中你使用了method="post",而在控制器类中你使用了@GetMapping。使用这个

      <input type="text" th:field="*{id}">
      

      而不是

      <input type="text" th:="*{id}"><br>
      

      还要在 Student 类中制作 id 属性的 getter/setter

      【讨论】:

      • java.lang.IllegalStateException: Bean 名称 'Student' 的 BindingResult 和普通目标对象都不能用作请求属性
      • 尝试使用 th:object="${student}" 而不是 th:object="${Student}"。此外,学生类必须在 @ComponnetScan 中使用的包下
      • 您能否确认正在应用程序上下文中加载学生表单 bean
      • 不,它没有在应用程序上下文中加载
      • 在applicationContext中加载这个Form Bean类,貌似是bean不可用的问题
      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2011-10-16
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多