【发布时间】:2018-03-30 13:39:57
【问题描述】:
我正在本地机器上使用 Sprint Tool Suite 开发 Java 创建我的第一个表单。我创建了一个带有 3 个输入字段的简单表单的 index.html 页面。我想让表单提交到一个 results.html 页面,该页面只显示输入到表单中的值。我遇到的问题是,当我启动应用程序时,填写一些数据,然后单击提交按钮,我收到 404 错误。另外,我注意到当我点击提交按钮时,浏览器的 url 框变为 localhost:8080/person。我希望看到 localhost:8080/results。提前感谢您的帮助。
我的主要应用类代码是这样的:
package com.baconbuddy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BaconBuddyApplication {
public static void main(String[] args) {
SpringApplication.run(BaconBuddyApplication.class, args);
}
}
我的 index.html 有以下代码:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Hello world!</h1>
<form action="#" th:action="@{/person}" th:object="${person}" method="post" >
<input th:field="*{firstName}" placeholder="First Name" />
<input th:field="*{lastName}" placeholder="Last Name" />
<input th:field="*{age}" placeholder="Age" />
<button >Submit</button>
</form>
</body>
</html>
我的 results.html 有以下代码:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<p>First Name:
<span th:text="${person.firstName}"></span>
</p>
<br />
<p>Last Name:
<span th:text="${person.lastName}"></span>
</p>
<br />
<p>Age:
<span th:text="${person.age}"></span>
</p>
</div>
</body>
</html>
我的 Person.java 文件如下所示:
package com.baconbuddy.models;
public class Person {
private String firstName;
private String lastName;
private int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
我的 HomeController.java 看起来像这样:
package com.baconbuddy.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baconbuddy.models.Person;
@Controller
@RequestMapping({ "/", "/home" })
public class HomeController {
@GetMapping()
public String index(Model model) {
model.addAttribute("person", new Person());
// The string index will be looked for in src/main/resources/templates
return "index";
}
@PostMapping()
public String personSubmit(@ModelAttribute Person person) {
return "results";
}
}
【问题讨论】: