📅  最后修改于: 2020-12-04 08:30:21             🧑  作者: Mango
Spring MVC表单文本字段标签使用绑定值生成HTML输入标签。默认情况下,输入标签的类型是文本。
在这里, path属性将form字段绑定到bean属性。
Spring MVC表单标签库还提供其他输入类型,例如电子邮件,日期,电话等。
让我们看一个使用表单标签库创建铁路预订表单的示例。
org.springframework
spring-webmvc
5.1.1.RELEASE
javax.servlet
servlet-api
3.0-alpha-1
javax.servlet
jstl
1.2
org.apache.tomcat
tomcat-jasper
9.0.12
在这里,bean类包含与表单中存在的输入字段相对应的变量(设置方法和获取方法)。
Reservation.java
package com.javatpoint;
public class Reservation {
private String firstName;
private String lastName;
public Reservation()
{
}
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;
}
}
ReservationController.java
package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/reservation")
@Controller
public class ReservationController {
@RequestMapping("/bookingForm")
public String bookingForm(Model model)
{
//create a reservation object
Reservation res=new Reservation();
//provide reservation object to the model
model.addAttribute("reservation", res);
return "reservation-page";
}
@RequestMapping("/submitForm")
// @ModelAttribute binds form data to the object
public String submitForm(@ModelAttribute("reservation") Reservation res)
{
return "confirmation-form";
}
}
web.xml
SpringMVC
spring
org.springframework.web.servlet.DispatcherServlet
1
spring
/
spring-servlet.xml
index.jsp
Railway Registration Form
Click here for reservation.
Reservation-page.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Reservation Form
Railway Reservation Form
First name:
Last name:
注-通过@ModelAttribute批注传递的值应与视图页面中存在的modelAttribute值相同。
确认页面.jsp
Your reservation is confirmed successfully. Please, re-check the details.
First Name : ${reservation.firstName}
Last Name : ${reservation.lastName}
输出: