1. 概述

本文将带你快速上手 Spring MVC 中的表单处理与数据绑定机制,重点介绍一个核心注解:***@ModelAttribute***。

当然,Spring MVC 是一个功能强大的框架,涉及的内容非常广泛。如果你希望深入学习,建议查阅更多相关资料,例如 Spring MVC 专题

2. 数据模型

首先,我们定义一个简单的实体类,用于承载表单数据:

public class Employee {
    private String name;
    private long id;
    private String contactNumber;

    // 标准的 getter 和 setter 方法
}

这个类就是我们常说的 form-backing object(表单支持对象)

3. 页面视图

接下来,我们构建一个 JSP 页面,用来展示并提交员工信息:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
    <head>
    </head>
    <body>
        <h3>Welcome, Enter The Employee Details</h3>
        <form:form method="POST" 
          action="/spring-mvc-xml/addEmployee" modelAttribute="employee">
             <table>
                <tr>
                    <td><form:label path="name">Name</form:label></td>
                    <td><form:input path="name"/></td>
                </tr>
                <tr>
                    <td><form:label path="id">Id</form:label></td>
                    <td><form:input path="id"/></td>
                </tr>
                <tr>
                    <td><form:label path="contactNumber">
                      Contact Number</form:label></td>
                    <td><form:input path="contactNumber"/></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Submit"/></td>
                </tr>
            </table>
        </form:form>
    </body>
</html>

✅ 关键点说明:

  • 引入了 Spring 的 form 标签库,简化表单构建。
  • <form:form> 标签与 HTML 的 <form> 类似,但多了 modelAttribute 属性,用于绑定后端对象(这里是 employee)。
  • 每个输入框通过 path 属性绑定到对象的字段(如 name, id 等),Spring 会自动调用 getter/setter 来填充或提交数据。

⚠️ 注意:

如果 JSP 页面中引用了 employee 这个 modelAttribute,但后端没有正确传递,就会抛出如下异常:

java.lang.IllegalStateException: 
  Neither BindingResult nor plain target object 
    for bean name 'employee' available as request attribute

📷 页面效果示意:

Basic Forms with Spring MVC

4. 控制器实现

后端控制器代码如下:

@Controller
public class EmployeeController {

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView showForm() {
        return new ModelAndView("employeeHome", "employee", new Employee());
    }

    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("employee") Employee employee, 
      BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "error";
        }
        model.addAttribute("name", employee.getName());
        model.addAttribute("contactNumber", employee.getContactNumber());
        model.addAttribute("id", employee.getId());
        return "employeeView";
    }
}

✅ 关键点说明:

  • showForm() 方法返回一个包含 employee 对象的 ModelAndView,用于初始化表单。
  • submit() 方法处理表单提交,使用 @ModelAttribute 绑定表单数据。
  • 如果绑定出错(比如类型不匹配),Spring 会将错误信息封装在 BindingResult 中。
  • 若未将 employee 对象加入 model,Spring 会报错提示找不到绑定对象。

5. 处理绑定错误

默认情况下,Spring MVC 在绑定失败时会直接抛异常。但在实际开发中,我们更希望将错误信息展示给用户。

为此,我们使用 BindingResult 来捕获绑定错误:

public String submit(
  @Valid @ModelAttribute("employee") Employee employee,
  BindingResult result,
  ModelMap model)

⚠️ 注意事项:

  • BindingResult 必须紧跟在 @ModelAttribute 参数后面,否则会抛出如下异常:
java.lang.IllegalStateException: 
  Errors/BindingResult argument declared without preceding model attribute. 
    Check your handler method signature!

✅ 错误处理示例:

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("employee") Employee employee, 
  BindingResult result, ModelMap model) {
    if (result.hasErrors()) {
        return "error";
    }
    // 正常处理逻辑
    return "employeeView";
}

❌ 错误页面示例(error.jsp):

<html>
    <head>
    </head>
    <body>
        <h3>Please enter the correct details</h3>
        <table>
            <tr>
                <td><a href="employee">Retry</a></td>
            </tr>
        </table>
    </body>
</html>

6. 展示员工信息

除了新增员工,我们也可以展示员工信息:

<body>
    <h2>Submitted Employee Information</h2>
    <table>
        <tr>
            <td>Name :</td>
            <td>${name}</td>
        </tr>
        <tr>
            <td>ID :</td>
            <td>${id}</td>
        </tr>
        <tr>
            <td>Contact Number :</td>
            <td>${contactNumber}</td>
        </tr>
    </table>
</body>

使用 JSP 的 EL 表达式 ${} 来输出模型中的属性值。

7. 应用测试

部署应用(例如部署到 Tomcat),访问如下地址:

http://localhost:8080/spring-mvc-xml/employee

你会看到一个表单页面,填写并提交后,系统会展示提交的数据。

✅ 示例项目地址:

GitHub 项目地址

这是一个 Maven 项目,可直接导入运行。


如我文章开头所说,Spring MVC 是一个值得深入研究的框架,建议你继续探索 更多 Spring MVC 内容


« 上一篇: Baeldung周报31
» 下一篇: Baeldung周报32