【发布时间】:2017-08-07 06:43:20
【问题描述】:
我正在研究 Spring MVC 中的数据绑定,并且正在接近使用标记形式来实现它。如前所述,似乎有必要在 Spring 框架中实现数据绑定。
但是我用Spring Boot做了一个测试,并没有使用form标签,甚至没有使用JSP页面进行输入,而只是一个外部的HTML页面。
那么,问题来了,form 标签是有用但不是必须的,还是只有 Spring Boot 才有用?
下面的代码。谢谢!
输入 HTML 表单
<html>
<body>
<h3> Registration Form <h3>
<br/>
<form action="http://localhost:8080/register" method="post" >
<pre>
Name <input type="text" name="name" />
Email address <input type="text" name="emailAddress" />
Password <input type="password" name="password" />
<input type="submit" value="Submit" />
</pre>
</form>
</body>
</html>
弹簧控制器:
package hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RegistrationController {
@RequestMapping("/register")
public String greeting(User user, Model model) {
model.addAttribute("user", user);
return "result";
}
}
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.example.bytecode</groupId>
<artifactId>SpringBootBindingForm</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
带有 Thymeleaf 的输出页面(为了验证正确的数据绑定)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Name, ' + ${user.name} + '!'" />
<p th:text="'Password, ' + ${user.password} + '!'" />
<p th:text="'Email, ' + ${user.emailAddress} + '!'" />
</body>
</html>
还有 User.java 和 Application.java 我认为没有必要在这里展示。
【问题讨论】:
标签: java spring spring-mvc spring-boot data-binding