SpringMVC处理form表单
最近在学习springmvc框架的东西,其中遇到一个很莫名的异常,在这里简单的记录一下,以备后期查阅。
针对前端传送过来的一个表单中的数据如果后台对应的action方法中没有跟form表单组成的实体相同名称的入参;那么就会报出异常:
先上一段前端form表单对应的一个action方法,注意其中没有任何的入参;
@RequestMapping("/profile")
public String displayProfile() {
return "profile/profilePage";
}
前端代码如下:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="layout/default"> <head lang="en"> <title>Your profile</title> </head> <body> <div class="row" layout:fragment="content"> <h2 class="indigo-text center">Personal info</h2> <form th:action="@{/profile}" method="post" th:object="${profileForm}" class="col m8 s12 offset-m2"> <div class="row"> <div class="input-field col s6"> <input th:filed="${profileForm.twitterHandle}" id="twitterHandle" type="text"/> <label for="twitterHandle">Twitter handle</label> </div> <div class="input-field col s6"> <input th:field="${profileForm.email}" id="email" type="email"/> <label for="email">Email</label> </div> </div> <div class="row"> <div class="input-field col s6"> <input th:field="${profileForm.birthDate}" id="birthDate" type="text"/> <label for="birthDate">Birth Date</label> </div> </div> <div class="row s12"> <button class="btn waves-effect waves-light" type="submit" name="save">Submit <i class="mdi-content-send right"></i> </button> </div> </form> </div> </body> </html>
运行并访问应用回展示如下的前端错误。
后端会报:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "profile", template might not exist or might not be accessible by any of the configured Template Resolvers
仔细查看了一下是由于自己没有在controler方法中加入请求参数,将action方法变为如下即可通过
@RequestMapping("/profile") public String displayProfile(ProfileForm profileForm) { return "profile/profilePage"; }
写的比较简单,在这里记录一下以备后查。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律