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项目之七 日期的使用和输出日志

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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