专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 SpringMVC的form表单处理

SpringMVC的form表单处理

更新时间:2021-09-10 09:59:56 来源:赢咖4 浏览933次

针对前端传送过来的一个表单中的数据如果后台对应的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";
    }

以上就是赢咖4小编介绍的"SpringMVC的form表单处理",希望对大家有帮助,想了解更多可查看SpringMVC教程。赢咖4在线学习教程,针对没有任何Java基础的读者学习,让你从入门到精通,主要介绍了一些Java基础的核心知识,让同学们更好更方便的学习和了解Java编程,感兴趣的同学可以关注一下。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>