Spring MVC-表单(Form)标签-错误处理(Error Handling)示例(转载实践)

以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_errors.htm

说明:示例基于Spring MVC 4.1.6。

以下示例显示了如何在使用Spring Web MVC框架的窗体中使用错误处理和验证器。首先,让我们使用Eclipse IDE,并按照以下步骤使用Spring Web Framework开发基于动态窗体的Web应用程序:

步骤 描述
1 创建一个名为HelloWeb的项目,在一个包com.tutorialspoint下,如Spring MVC - Hello World Example章节所述。
2 在com.tutorialspoint包下创建一个Java类Student,StudentController和StudentValidator。
3 创建一个视图文件addStudent.jsp,result.jsp中下JSP子文件夹中。
4 最后一步是创建所有源和配置文件的内容并导出应用程序,如下所述。

Student.java

package com.tutorialspoint;

public class Student {
   private Integer age;
   private String name;
   private Integer id;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }

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

   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

StudentValidator.java

package com.tutorialspoint;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class StudentValidator implements Validator {

   @Override
   public boolean supports(Class<?> clazz) {
      return Student.class.isAssignableFrom(clazz);
   }

   @Override
   public void validate(Object target, Errors errors) {
      ValidationUtils.rejectIfEmptyOrWhitespace(errors,
         "name", "required.name","Field name is required.");
   }
}

StudentController.java

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController {

   @Autowired
   @Qualifier("studentValidator")
   private Validator validator;

   @InitBinder
   private void initBinder(WebDataBinder binder) {
      binder.setValidator(validator);
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("addStudent", "command", new Student());
   }

   @ModelAttribute("student")
   public Student createStudentModel() {
      return new Student();
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute("student") @Validated Student student,
      BindingResult bindingResult, Model model) {

      if (bindingResult.hasErrors()) {
         return "addStudent";
      }
      model.addAttribute("name", student.getName());
      model.addAttribute("age", student.getAge());
      model.addAttribute("id", student.getId());

      return "result";
   }
}

HelloWeb-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.tutorialspoint" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

   <bean id="studentValidator" class="com.tutorialspoint.StudentValidator" />
</beans>

这里第一个服务方法student(),我们已经在ModelAndView对象中传递了一个空白的Student对象,名称为“command”,因为如果您在JSP中使用<form:form>标签,Spring框架会期望一个名为“command”的对象文件。所以当调用student()方法时,返回addStudent.jsp视图。

将在HelloWeb/addStudent URL 上针对POST方法调用第二个服务方法addStudent()。您将根据提交的信息准备您的模型对象。最后,将从服务方法返回“result”视图,这将导致渲染result.jsp。如果使用验证器生成错误,则返回相同视图“addStudent”,Spring会自动从BindingResult注入错误消息。

addStudent.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<style>
.error {
   color: #ff0000;
}

.errorblock {
   color: #000;
   background-color: #ffEEEE;
   border: 3px solid #ff0000;
   padding: 8px;
   margin: 16px;
}
</style>
<body>

<h2>Student Information</h2>
<form:form method="POST" action="/HelloWeb/addStudent" commandName="student">
   <form:errors path="*" cssClass="errorblock" element="div" />
   <table>
    <tr>
        <td><form:label path="name">Name</form:label></td>
        <td><form:input path="name" /></td>
        <td><form:errors path="name" cssClass="error" /></td>
    </tr>
    <tr>
        <td><form:label path="age">Age</form:label></td>
        <td><form:input path="age" /></td>
    </tr>
    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>
</form:form>
</body>
</html>

这里我们使用带有path ="*"的<form:errors />标签来显示错误消息。例如

<form:errors path="*" cssClass="errorblock" element="div" />

它将为所有输入验证提供错误消息。

而且我们使用path="name"的<form:errors />标签来显示name字段的错误消息。例如

<form:errors path="name" cssClass="error" />

它会显示名称字段验证的错误消息。

result.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Submitted Student Information</h2>
   <table>
    <tr>
        <td>Name</td>
        <td>${name}</td>
    </tr>
    <tr>
        <td>Age</td>
        <td>${age}</td>
    </tr>
    <tr>
        <td>ID</td>
        <td>${id}</td>
    </tr>
</table>
</body>
</html>

完成创建源文件和配置文件后,导出应用程序。右键单击应用程序并使用Export->WAR File选项,并将您的HelloWeb.war文件保存在Tomcat的webapps文件夹中。

现在启动您的Tomcat服务器,并确保您可以使用标准浏览器从webapps文件夹访问其他网页。现在尝试URL http://localhost:8080/HelloWeb/addStudent,如果Spring Web应用程序的一切都很好,您应该会看到以下结果:

提交所需信息后,点击提交按钮提交表单。如果您的Spring Web应用程序的一切都很好,您应该会看到以下结果:

Maven示例:

https://github.com/easonjim/5_java_example/tree/master/springmvc/tutorialspoint/test14

时间: 2024-08-07 16:59:04

Spring MVC-表单(Form)标签-错误处理(Error Handling)示例(转载实践)的相关文章

spring mvc表单form值自动传到javabean-注解@ModelAttribute

直接通过Form Bean进行表单可以简化表单提交的处理,特别是对于复杂表单,过于简单的表单就不建议了,因为毕竟需要额外创建一个Form Bean. 前段时间项目中有一个比较复杂的表单,有多层次而且涉及数组,如果不采用Form Bean的处理方式会比较麻烦,但多层而且是数组,之前一直没有找到如何通过Form Bean方式进行处理,但相信Spring MVC应该可以做到,因为Spring的强大之处就是IOC嘛,所以在网上查阅资料,并不断尝试后终于解决,现在不管是多么复杂的表单均可以通过Form B

Spring MVC - 表单处理示例

环境搭建 环境: Intellij IDEA Spring MVC 完整的项目文件结构如下所示: Student.java package com.ktao.controller; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge(

spring mvc表单修改提交

实际应用中,列表中的单条记录的修改,可能需要传很多对象参数到后台服务器,Spring MVC表单标签<form:> 提供了一种简洁的提交方式. 1 <form id="form1" class="form-horizontal chukong_form" method="post" 2 action="${ctx}/channel/sdkversion/postedit.do"> 3 <form:

Spring MVC表单提交

实际应用中,列表中的单条记录的修改,可能需要传很多对象参数到后台服务器,Spring MVC表单标签<form:> 提供了一种简洁的提交方式. 1 <form id="form1" class="form-horizontal chukong_form" method="post" action="${ctx}/channel/sdkversion/postedit.do"> 3 <form:hi

spring mvc表单的展现、输入处理、校验的实现

之前已经实现了spring mvc的入门例子及如何处理带参数的请求Controller编写.本文主要记录: 1)重定向请求 2)处理路径中含有变量的请求 3)使用JSR-303进行校验 ① 首先,编写一个方法实现一个表单的展现: //展示表单    //params 可限制该方法只对包含特定参数的请求进行处理    @RequestMapping(method=RequestMethod.GET,params="new")    public String createForm(Mod

Spring MVC 表单验证

1. 基于 JSR-303(一个数据验证的规范): import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; public class User { private String username; private String password; private int age

Spring MVC笔记(三) Spring MVC表单处理

创建动态WEB工程 FormHandling,并添加SpringMVC相关jar包(同Hello world示例一致),添加DispatcherServlet配置,如下: web.xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http

Java单体应用 - 常用框架 - 07.Spring MVC - 表单标签库

原文地址:http://www.work100.net/training/monolithic-frameworks-spring-mvc-form-tags.html更多教程:光束云 - 免费课程 表单标签库 序号 文内章节 视频 1 声明表单标签 - 2 表单标签 - 3 文本框 - 4 密码框 - 5 文本域 - 6 复选框 - 7 复选框(多选) - 8 单选按钮 - 9 单选按钮(多选) - 10 下拉列表 - 11 下拉列表(多选) - 12 隐藏域 - 请参照如上章节导航进行阅读

Spring MVC 表单提交

下面的例子展示了如何编写一个简单的基于Web的应用程序,它利用了使用Spring的Web MVC框架的HTML表单.要开始使用它,使用Eclipse IDE,并按照以下步骤使用Spring Web框架开发动态表单的Web应用程序: 步骤 描述 1 Create a Dynamic Web Project with a name HelloWeb and create a packagecom.yiibai under the src folder in the created project.

WEB前端开发学习----3.HTML表单form标签

什么是表单? 表单就是用来搜集不同类型的用户输入.比如我们登录时输入的登录名,密码.再比如我们点击登录按钮,删除按钮等等都算是表单. 表单是一个包含表单元素的区域,包括文本域,下拉菜单,复选框,单选框等等. 在html文档中,我们使用<form></form>标签来包含表单元素. form标签有两个属性需要注意下,一个是action, 另一个是method. action ="目的地"   表示将用户输入的数据将被传送到指定位置.比如一个网页. method=&