Form Validation with AngularJS and Spring MVC – 用AngularJS和Spring MVC进行表单验证

最后修改: 2017年 3月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Validation is never quite as straightforward as we expect. And of course validating the values entered by a user into an application is very important for preserving the integrity of our data.

验证从来都不像我们期望的那样简单。当然,验证用户在应用程序中输入的值对于保护我们数据的完整性是非常重要的。

In the context of a web application, data input is usually done using HTML forms and requires both client-side and server-side validation.

在网络应用的背景下,数据输入通常使用HTML表单,并需要客户端和服务器端的验证。

In this tutorial, we’ll have a look at implementing client-side validation of form input using AngularJS and server-side validation using the Spring MVC framework.

在本教程中,我们将看看使用AngularJS实现表单输入的客户端验证和使用Spring MVC框架实现服务器端验证

This article focuses on Spring MVC. Our article Validation in Spring Boot describes how to do validations in Spring Boot.

本文主要介绍Spring MVC。我们的文章Spring Boot中的验证介绍了如何在Spring Boot中进行验证。

2. Maven Dependencies

2.Maven的依赖性

To start off, let’s add the following dependencies:

首先,让我们添加以下依赖项。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.0.Final</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

The latest versions of spring-webmvc, hibernate-validator and jackson-databind can be downloaded from Maven Central.

spring-webmvchibernate-validatorjackson-databind的最新版本可以从Maven中心下载。

3. Validation Using Spring MVC

3.使用Spring MVC进行验证

An application should never rely solely on client-side validation, as this can be easily circumvented. To prevent incorrect or malicious values from being saved or causing improper execution of the application logic, it is important to validate input values on the server side as well.

一个应用程序不应该仅仅依靠客户端的验证,因为这很容易被规避。为了防止不正确的或恶意的值被保存或导致应用逻辑的不正常执行,在服务器端验证输入值也很重要。

Spring MVC offers support for server-side validation by using JSR 349 Bean Validation specification annotations. For this example, we will use the reference implementation of the specification, which is hibernate-validator.

Spring MVC通过使用JSR 349 Bean Validation规范注解,为服务器端验证提供了支持。在这个例子中,我们将使用该规范的参考实现,也就是hibernate-validator

3.1. The Data Model

3.1.数据模型

Let’s create a User class that has properties annotated with appropriate validation annotations:

让我们创建一个User类,它的属性用适当的验证注解来注解。

public class User {

    @NotNull
    @Email
    private String email;

    @NotNull
    @Size(min = 4, max = 15)
    private String password;

    @NotBlank
    private String name;

    @Min(18)
    @Digits(integer = 2, fraction = 0)
    private int age;

    // standard constructor, getters, setters
}

The annotations used above belong to the JSR 349 specification, with the exception of @Email and @NotBlank, which are specific to the hibernate-validator library.

上面使用的注解属于JSR 349规范,但@Email@NotBlank除外,它们是hibernate-validator库特有的。

3.2. Spring MVC Controller

3.2.Spring MVC控制器

Let’s create a controller class that defines a /user endpoint, which will be used to save a new User object to a List.

让我们创建一个控制器类,定义一个/user端点,它将被用来保存一个新的User对象到一个List

In order to enable validation of the User object received through request parameters, the declaration must be preceded by the @Valid annotation, and the validation errors will be held in a BindingResult instance.

为了使通过请求参数收到的User对象得到验证,声明必须在前面加上@Valid注解,而且验证错误将被保存在BindingResult实例中。

To determine if the object contains invalid values, we can use the hasErrors() method of BindingResult.

为了确定对象是否包含无效的值,我们可以使用BindingResulthasErrors()方法。

If hasErrors() returns true, we can return a JSON array containing the error messages associated with the validations that did not pass. Otherwise, we will add the object to the list:

如果hasErrors()返回true,我们可以返回一个JSON数组,包含与未通过的验证相关的错误信息。否则,我们将把该对象添加到列表中。

@PostMapping(value = "/user")
@ResponseBody
public ResponseEntity<Object> saveUser(@Valid User user, 
  BindingResult result, Model model) {
    if (result.hasErrors()) {
        List<String> errors = result.getAllErrors().stream()
          .map(DefaultMessageSourceResolvable::getDefaultMessage)
          .collect(Collectors.toList());
        return new ResponseEntity<>(errors, HttpStatus.OK);
    } else {
        if (users.stream().anyMatch(it -> user.getEmail().equals(it.getEmail()))) {
            return new ResponseEntity<>(
              Collections.singletonList("Email already exists!"), 
              HttpStatus.CONFLICT);
        } else {
            users.add(user);
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
    }
}

As you can see, server-side validation adds the advantage of having the ability to perform additional checks that are not possible on the client side.

正如你所看到的,服务器端验证增加了具有执行额外检查的能力的优势,这在客户端是不可能的。

In our case, we can verify whether a user with the same email already exists – and return a status of 409 CONFLICT if that’s the case.

在我们的案例中,我们可以验证是否已经存在一个具有相同电子邮件的用户–如果是这样的话,则返回409 CONFLICT状态。

We also need to define our list of users and initialize it with a few values:

我们还需要定义我们的用户列表,并用一些值来初始化它。

private List<User> users = Arrays.asList(
  new User("ana@yahoo.com", "pass", "Ana", 20),
  new User("bob@yahoo.com", "pass", "Bob", 30),
  new User("john@yahoo.com", "pass", "John", 40),
  new User("mary@yahoo.com", "pass", "Mary", 30));

Let’s also add a mapping for retrieving the list of users as a JSON object:

让我们也添加一个映射,以JSON对象的形式检索用户列表。

@GetMapping(value = "/users")
@ResponseBody
public List<User> getUsers() {
    return users;
}

The final item we need in our Spring MVC controller is a mapping to return the main page of our application:

我们在Spring MVC控制器中需要的最后一项是一个映射,用来返回我们应用程序的主页面。

@GetMapping("/userPage")
public String getUserProfilePage() {
    return "user";
}

We will take a look at the user.html page in more detail in the AngularJS section.

我们将在AngularJS部分更详细地查看 user.html页面。

3.3. Spring MVC Configuration

3.3.Spring MVC配置

Let’s add a basic MVC configuration to our application:

让我们为我们的应用程序添加一个基本的MVC配置。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.springmvcforms")
class ApplicationConfiguration implements WebMvcConfigurer {

    @Override
    public void configureDefaultServletHandling(
      DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver htmlViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/html/");
        bean.setSuffix(".html");
        return bean;
    }
}

3.4. Initializing the Application

3.4.初始化应用程序

Let’s create a class that implements WebApplicationInitializer interface to run our application:

让我们创建一个实现WebApplicationInitializer接口的类来运行我们的应用程序。

public class WebInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx
          = new AnnotationConfigWebApplicationContext();
        ctx.register(ApplicationConfiguration.class);
        ctx.setServletContext(container);
        container.addListener(new ContextLoaderListener(ctx));

        ServletRegistration.Dynamic servlet 
          = container.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

3.5. Testing Spring Mvc Validation Using Curl

3.5.使用Curl测试Spring Mvc的验证

Before we implement the AngularJS client section, we can test our API using cURL with the command:

在我们实现AngularJS客户端部分之前,我们可以用cURL的命令测试我们的API。

curl -i -X POST -H "Accept:application/json" 
  "localhost:8080/spring-mvc-forms/user?email=aaa&password=12&age=12"

The response is an array containing the default error messages:

响应是一个包含默认错误信息的数组。

[
    "not a well-formed email address",
    "size must be between 4 and 15",
    "may not be empty",
    "must be greater than or equal to 18"
]

4. AngularJS Validation

4.AngularJS的验证

Client-side validation is useful in creating a better user experience, as it provides the user with information on how to successfully submit valid data and enables them to be able to continue to interact with the application.

客户端验证对于创造更好的用户体验非常有用,因为它为用户提供了如何成功提交有效数据的信息,并使他们能够继续与应用程序互动。

The AngularJS library has great support for adding validation requirements on form fields, handling error messages, and styling valid and invalid forms.

AngularJS库对在表单字段上添加验证要求、处理错误信息以及对有效和无效的表单进行样式设计有很大的支持。

First, let’s create an AngularJS module that injects the ngMessages module, which is used for validation messages:

首先,让我们创建一个AngularJS模块,注入ngMessages模块,它用于验证信息。

var app = angular.module('app', ['ngMessages']);

Next, let’s create an AngularJS service and controller that will consume the API built in the previous section.

接下来,让我们创建一个AngularJS服务和控制器,它将消费上一节中构建的API。

4.1. The AngularJS Service

4.1.AngularJS服务

Our service will have two methods that call the MVC controller methods — one to save a user, and one to retrieve the list of users:

我们的服务将有两个方法调用MVC控制器的方法–一个用于保存用户,一个用于检索用户列表。

app.service('UserService',['$http', function ($http) {
	
    this.saveUser = function saveUser(user){
        return $http({
          method: 'POST',
          url: 'user',
          params: {email:user.email, password:user.password, 
            name:user.name, age:user.age},
          headers: 'Accept:application/json'
        });
    }
	
    this.getUsers = function getUsers(){
        return $http({
          method: 'GET',
          url: 'users',
          headers:'Accept:application/json'
        }).then( function(response){
        	return response.data;
        } );
    }

}]);

4.2. The AngularJS Controller

4.2.AngularJS控制器

The UserCtrl controller injects the UserService, calls the service methods and handles the response and error messages:

UserCtrl控制器注入UserService,调用服务方法并处理响应和错误信息。

app.controller('UserCtrl', ['$scope','UserService', function ($scope,UserService) {
	
	$scope.submitted = false;
	
	$scope.getUsers = function() {
		   UserService.getUsers().then(function(data) {
		       $scope.users = data;
	       });
	   }
    
    $scope.saveUser = function() {
    	$scope.submitted = true;
    	  if ($scope.userForm.$valid) {
            UserService.saveUser($scope.user)
              .then (function success(response) {
                  $scope.message = 'User added!';
                  $scope.errorMessage = '';
                  $scope.getUsers();
                  $scope.user = null;
                  $scope.submitted = false;
              },
              function error(response) {
                  if (response.status == 409) {
                    $scope.errorMessage = response.data.message;
            	  }
            	  else {
                    $scope.errorMessage = 'Error adding user!';
            	  }
                  $scope.message = '';
            });
    	  }
    }
   
   $scope.getUsers();
}]);

We can see in the example above that the service method is called only if the $valid property of userForm is true. Still, in this case, there is the additional check for duplicate emails, which can only be done on the server and is handled separately in the error() function.

我们可以在上面的例子中看到,只有当userForm$valid属性为真时,才会调用服务方法。不过,在这种情况下,还有额外的重复邮件检查,这只能在服务器上进行,并在error()函数中单独处理。

Also, notice that there is a submitted variable defined which will tell us if the form has been submitted or not.

另外,注意到有一个submitted变量被定义,它将告诉我们表单是否被提交。

Initially, this variable will be false, and on invocation of the saveUser() method, it becomes true. If we don’t want validation messages to show before the user submits the form, we can use the submitted variable to prevent this.

最初,这个变量将是false,在调用saveUser()方法时,它会变成true。如果我们不希望在用户提交表单之前显示验证信息,我们可以使用submitted变量来防止这种情况。

4.3. Form Using AngularJS Validation

4.3.使用AngularJS验证的表单

In order to make use of the AngularJS library and our AngularJS module, we will need to add the scripts to our user.html page:

为了利用AngularJS库和我们的AngularJS模块,我们将需要把脚本添加到我们的user.html页面。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js">
</script>
<script src="js/app.js"></script>

Then we can use our module and controller by setting the ng-app and ng-controller properties:

然后我们可以通过设置ng-appng-controller属性来使用我们的模块和控制器。

<body ng-app="app" ng-controller="UserCtrl">

Let’s create our HTML form:

让我们来创建我们的HTML表单。

<form name="userForm" method="POST" novalidate 
  ng-class="{'form-error':submitted}" ng-submit="saveUser()" >
...
</form>

Note that we have to set the novalidate attribute on the form in order to prevent default HTML5 validation and replace it with our own.

注意,我们必须在表单上设置novalidate属性,以阻止默认的HTML5验证,并用我们自己的验证来取代它。

The ng-class attribute adds the form-error CSS class dynamically to the form if the submitted variable has a value of true.

如果submitted变量的值为trueng-class属性会将form-error CSS类动态地添加到表单中。

The ng-submit attribute defines the AngularJS controller function that will be called when the form in submitted. Using ng-submit instead of ng-click has the advantage that it also responds to submitting the form using the ENTER key.

ng-submit属性定义了AngularJS控制器函数,当表单被提交时将被调用。使用ng-submit而不是ng-click的好处是,它也会对使用ENTER键提交表单做出反应。

Now let’s add the four input fields for the User attributes:

现在让我们为用户属性添加四个输入字段。

<label class="form-label">Email:</label>
<input type="email" name="email" required ng-model="user.email" class="form-input"/>

<label class="form-label">Password:</label>
<input type="password" name="password" required ng-model="user.password" 
  ng-minlength="4" ng-maxlength="15" class="form-input"/>

<label class="form-label">Name:</label>
<input type="text" name="name" ng-model="user.name" ng-trim="true" 
  required class="form-input" />

<label class="form-label">Age:</label>
<input type="number" name="age" ng-model="user.age" ng-min="18"
  class="form-input" required/>

Each input field has a binding to a property of the user variable through the ng-model attribute.

每个输入字段都通过ng-model属性绑定到user变量的一个属性。

For setting validation rules, we use the HTML5 required attribute and several AngularJS-specific attributes: ng-minglength, ng-maxlength, ng-min, and ng-trim.

对于设置验证规则,我们使用HTML5的required属性和几个AngularJS特有的属性。ng-minglength, ng-maxlength, ng-min, ng-trim

For the email field, we also use the type attribute with a value of email for client-side email validation.

对于email字段,我们也使用type属性,其值为email,用于客户端的电子邮件验证。

In order to add error messages corresponding to each field, AngularJS offers the ng-messages directive, which loops through an input’s $errors object and displays messages based on each validation rule.

为了添加与每个字段相对应的错误信息,AngularJS提供了ng-messages指令,该指令循环浏览输入的$errors对象并根据每个验证规则显示信息。

Let’s add the directive for the email field right after the input definition:

让我们在输入定义之后为email字段添加指令。

<div ng-messages="userForm.email.$error" 
  ng-show="submitted && userForm.email.$invalid" class="error-messages">
    <p ng-message="email">Invalid email!</p>
    <p ng-message="required">Email is required!</p>
</div>

Similar error messages can be added for the other input fields.

可以为其他输入字段添加类似的错误信息。

We can control when the directive is displayed for the email field using the ng-show property with a boolean expression. In our example, we display the directive when the field has an invalid value, meaning the $invalid property is true, and the submitted variable is also true.

我们可以使用带有布尔表达式的ng-show属性来控制何时为email字段显示指令。在我们的例子中,当字段有一个无效的值时,我们会显示指令,这意味着$invalid属性为true,并且submitted变量也为true

Only one error message will be displayed at a time for a field.

一个字段每次只显示一条错误信息。

We can also add a check mark sign (represented by HEX code character ✓) after the input field in case the field is valid, depending on the $valid property:

根据$valid属性,我们还可以在输入字段后添加一个复选标志(用HEX代码字符✓表示),以防字段有效。

<div class="check" ng-show="userForm.email.$valid">✓</div>

AngularJS validation also offers support for styling using CSS classes such as ng-valid and ng-invalid or more specific ones like ng-invalid-required and ng-invalid-minlength.

AngularJS验证还提供了对使用CSS类的造型支持,如ng-validng-invalid或更具体的如ng-invalid-requiredng-invalid-minlength

Let’s add the CSS property border-color:red for invalid inputs inside the form’s form-error class:

让我们在表单的form-error类中为无效的输入添加CSS属性border-color:red

.form-error input.ng-invalid {
    border-color:red;
}

We can also show the error messages in red using a CSS class:

我们也可以用一个CSS类将错误信息显示为红色。

.error-messages {
    color:red;
}

After putting everything together, let’s see an example of how our client-side form validation will look when filled out with a mix of valid and invalid values:

把所有东西放在一起后,让我们看一个例子,说明我们的客户端表单验证在填写了有效和无效的值后会是什么样子。

AngularJS form validation example

5. Conclusion

5.结论

In this tutorial, we’ve shown how we can combine client-side and server-side validation using AngularJS and Spring MVC.

在本教程中,我们展示了如何使用AngularJS和Spring MVC结合客户端和服务器端验证。

As always, the full source code for the examples can be found over on GitHub.

一如既往,可以在GitHub上找到这些例子的完整源代码

To view the application, access the /userPage URL after running it.

要查看应用程序,运行后访问/userPage URL。