Spring Boot框架开发Web项目之六 表单数据提交

本系列文章主要索引详情 点击查看


现在我们已经可以看到一个比较精美的页面了,但是它还无法完成任何功能,因为它还没有为它的post URL(表单提交方式为POST)映射任何的行为。

工具

IntelliJ IDEA 16
JDK 1.8
Maven 3.5
Tomcat 1.8

表单数据提交

1、创建一个数据传输对象(Data Transfer Object, DTO),新建与conroller同级的包dto,并在dto下新建名为 ProfileForm的java文件,它的作用是匹配web表单中的域病描述校验规则:

package com.example.dto;


public class ProfileForm {
    private String twitterHandle;
    private String email;
    private String birthDate;

    public String getTwitterHandle() {
        return twitterHandle;
    }

    public void setTwitterHandle(String twitterHandle) {
        this.twitterHandle = twitterHandle;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(String birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return "ProfileForm{" +
                "twitterHandle='" + twitterHandle + '\'' +
                ", email='" + email + '\'' +
                ", birthDate='" + birthDate + '\'' +
                '}';
    }
}

这是一个常规的简单老式Java对象(Plain Old Java Object, POJO)。必须生成getter和setter方法,否则的话数据绑定就无法正常运行了。
2、为了让Spring将表单域绑定到DTO上,我们需要在profilePage.html上添加一些元数据:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http:www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout/default">
<head>
    <meta charset="UTF-8"/>
    <title>Your profile</title>
</head>
<body>
    <div class="row" layout:fragment="content">

        <h2 class="indigo-text center">Prosonal info</h2>

        <form th:action="@{/profile}" th:object="${profileForm}" method="post" class="col m8 s11 offset-m2" >
            <div class="row">
                <div class="input-field col s6">
                    <input th:field="${profileForm.twitterHandle}" id="twitterHandle" type="text" />
                    <label for="twitterHandle">Last name</label>
                </div>
                <div class="input-field col s6">
                    <input th:field="${profileForm.email}" id="email" type="text" />
                    <label for="email">Email</label>
                </div>
            </div>

            <div class="row">
                <div class="input-field col s6">
                    <input id="birthDate" type="text" th:field="${profileForm.birthDate}"/>
                    <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-snd right"></i> </button>
            </div>
        </form>

    </div>
</body>
</html>

与之前版本的profilePage的差别如下图


在这里需要注意两个地方:
(1)表单上的th:object属性,用于表单数据对象绑定,将表单绑定到后台controller的一个JavaBean参数。
(2)所有输入域上的th:field属性,用于字段绑定。
3、为了让th:object能够运行起来,我们需要添加一个ProfileFrom类型的参数到请求映射的方法中:

package com.example.controller;

import com.example.dto.ProfileForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ProfileController {

    @RequestMapping("/profile")
    public String displayProfile(ProfileForm profileForm){
        return "profile/profilePage";
    }

    @RequestMapping(value = "/profile" ,method = RequestMethod.POST)
    public String saveProfile(ProfileForm profileForm){
        System.out.println("Save Ok"+profileForm);
        return "redirect:/profile";
    }
}

注意:此时如果我们使用 http://localhost:8080/profile进行跳转到profilePage页面,则ProfileController中的displayProfile方法必须加上ProfileForm对象的参数,否则会报错


错误提示:

[nio-8081-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8081-exec-1] Exception processing template "profile/profilePage": Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (profile/profilePage:17)
 [nio-8081-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (profile/profilePage:17)] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'profileForm' available as request attribute
    ......

4、访问http://localhost:8080/profile,进入


5、在表单中输入数据,并提交,我们将可以在后台看到打印的表单数据

上一篇:Spring Boot框架开发Web项目之五 使用Webjars实现质感设计

下一篇: Spring Boot框架开发Web项目之七 日期的使用和输出日志

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,679评论 6 342
  • 本系列文章主要索引详情 点击查看 通常情况下,我们都不希望用户输入非法的信息,这样的话,我们就需要对表单添加一些校...
    开心跳蚤阅读 1,467评论 0 4
  • 有一首《四季之歌》,无论谁喜爱春、夏、秋、冬,分别都是心地纯洁、意志坚强、感情深重、胸怀宽广的人,但是否略显“天真...
    明哥明说阅读 344评论 0 1