本文将展示如何使用jQuery.ajax将HTML表单请求发送到Spring REST API并返回JSON响应。
使用的工具 :
1. 项目结构创建一个标准的Maven项目:ajax-example,用于演示在Spring Boot中使用Ajax技术,搜索用户信息。其结构如下图所示 -
2. 项目依赖文件:pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> <modelVersion>4.0.0</modelVersion> <groupId>com.yiibai</groupId> <artifactId>ajax-example</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 3. Spring REST APIREST控制器,接受一个SearchCriteria并返回一个ResponseEntity。
一个正常的Spring Boot依赖和一些webjars资源。文件:SearchController.java 如下所示 -
package com.yiibai.controller; import com.yiibai.model.AjaxResponseBody; import com.yiibai.model.SearchCriteria; import com.yiibai.model.User; import com.yiibai.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import java.util.stream.Collectors; @RestController public class SearchController { UserService userService; @Autowired public void setUserService(UserService userService) { this.userService = userService; } @PostMapping("/api/search") public ResponseEntity<?> getSearchResultViaAjax(@Valid @RequestBody SearchCriteria search, Errors errors) { AjaxResponseBody result = new AjaxResponseBody(); //If error, just return a 400 bad request, along with the error message if (errors.hasErrors()) { result.setMsg(errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(","))); return ResponseEntity.badRequest().body(result); } List<User> users = userService.findByUserNameOrEmail(search.getUsername()); if (users.isEmpty()) { result.setMsg("no user found!"); } else { result.setMsg("success"); } result.setResult(users); return ResponseEntity.ok(result); } }一些其它的POJO类,它们分别如下所示 -
文件:AjaxResponseBody.java
文件:User.java
package com.yiibai.model; public class User { String username; String password; String email; public User(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + '}'; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }验证器类:SearchCriteria.java
package com.yiibai.model; import org.hibernate.validator.constraints.NotBlank; public class SearchCriteria { @NotBlank(message = "username can't empty!") String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }