Spring处理表单提交

本文详细介绍了如何使用Spring MVC处理表单提交的过程,包括创建Controller、显示和处理表单,以及运行示例。通过注解配置,Spring MVC简化了表单与对象绑定的操作,使得开发者能更专注于业务逻辑。
摘要由CSDN通过智能技术生成

Spring处理表单提交 由David发表在天码营 

今天我们来讲一个最简单的表单提交处理的例子,通过提交一个表单给朋友打一声招呼!

看这边文章之前,你至少应该了解基于Spring的Web开发的基础知识,需要补课的赶紧戳这里。​当然,你还是应该准备好开发环境:

  • IDE+Java环境(JDK 1.7或以上版本)
  • Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装)

准备POM文件

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.tianmaying</groupId>
  <artifactId>springboot-form-submission-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-form-submission-demo</name>
  <description>Springboot form submission demo</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
    <relativePath/>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

创建Controller

我们已经知道可以通过Controller来进行URL路由,Spring WebMvc框架会将Servlet容器里收到的HTTP请求根据路径分发给对应的@Controller类进行处理、而 @RequestMapping注解表明该方法处理那些URL对应的HTTP请求。

我们的SayHelloController的代码如下:

package com.tianmaying.springboot.formsubmission;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SayHelloController {

    @RequestMapping(value="/sayhello", method=RequestMethod.GET)
    public String sayHelloForm(Model model) {
        model.addAttribute("helloMessage", new HelloMessage());
        return "sayhello";
    }

    @RequestMapping(value="/sayhello", method=RequestMethod.POST)
    public String sayHello(@ModelAttribute HelloMessage helloMessage, Model model) {
        model.addAttribute("helloMessage", helloMessage);
        return "message";
    }

}
  • 针对/sayhelloGET请求,我们返回提交表单的页面,即sayHello.html
  • 针对/sayhelloPOST请求,我们进行表单的处理,然后将打招呼的信息渲染到message.html页面返回。

表单处理也无外乎这两件事情:显示表单,处理表单提交。

显示表单

/sayhelloGET请求里,在渲染页面之前,我们通过model.addAttribute("helloMessage", new HelloMessage());告诉页面绑定到一个空的HelloMessage对象,这样sayHello.html页面初始时就会显示一个空白的表单。

HelloMessage

package com.tianmaying.springboot.formsubmission;

public class HelloMessage {

    private String name;
    private String message;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

}

仅仅扔一个空白对象给表单还不够,你还得告诉表单的各个输入如何绑定到对象的各个属性上。这个时候我们要用上Themeleaf了。

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>天码营经验: Spring表单提交处理</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>表单处理演示</h1>
    <form action="#" th:action="@{/sayhello}" th:object="${helloMessage}" method="post">
        <p>friend: <input type="text" th:field="*{name}" /></p>
        <p>message: <input type="text" th:field="*{message}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>
  • th:action="@{/sayhello}"表示将表单提交的POST请求交给/sayhello这个URL来处理
  • th:object="${helloMessage}"表示用来搜集的表单数据的对象时helloMessage,即用户输入信息将存储于这个对象中
  • 两个表单域分别增加了属性th:field="*{name}"th:field="*{message}",这就是将一个表单域绑定到特定的对象属性

处理表单

把处理表单的Controller代码再单独拿出来:

    @RequestMapping(value="/sayhello", method=RequestMethod.POST)
    public String greetingSubmit(@ModelAttribute HelloMessage helloMessage, Model model) {
        model.addAttribute("helloMessage", helloMessage);
        return "message";
    }

处理表单就非常简单了,通过@ModelAttribute,我们可以直接通过helloMessage对象来处理用户提交的信息了。

David是从JSP和Servlet时代过来的人,对从request中根据参数名称逐个获取信息,然后自己去设置对应对象属性的场景依然历历在目,惨绝人寰哪。现在我们只需专注于Model的业务逻辑处理了,Spring MVC和Thymeleaf这对黄金组合帮我们搞定了表单和对象绑定这样繁琐的事情。

Run起来

这应该是你很熟悉的代码了:

package com.tianmaying.springboot.formsubmission;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

SpringBootApplication标注做的事情参考这里mvn spring-boot:run或在IDE中运行main()方法就可以看到效果了!​不用装Web服务器不用部署就能直接Run Web应用的感觉确实很酸爽!

当然,一个成熟的应用,通常还需要做表单的验证操作,即确保用户提交上来的数据是合法而且有效的!且待下回分解!


更多文章请访问天码营网站



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值