当前位置:   article > 正文

Spring Boot Ajax 详解_springboot ajax {“”,[]}

springboot ajax {“”,[]}

Spring Boot Ajax示例

本文将向您展示如何使用jQuery.ajaxHTML表单请求发送Spring REST API并返回JSON响应。

使用的工具 :

  1. Spring Boot 1.5.1.RELEASE
  2. 春季4.3.6.RELEASE
  3. Maven 3
  4. jQuery的
  5. Bootstrap 3

注意
您可能会对这个经典的Spring MVC Ajax示例感兴趣

1.项目结构

标准的Maven项目结构。

spring boot ajax的例子

 

2.项目依赖

一个正常的Spring Boot依赖项和一些webjars资源。

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/maven-v4_0_0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.mkyong</groupId>
  7. <artifactId>spring-boot-ajax-example</artifactId>
  8. <packaging>jar</packaging>
  9. <version>1.0</version>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>1.5.1.RELEASE</version>
  14. </parent>
  15. <properties>
  16. <java.version>1.8</java.version>
  17. </properties>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-devtools</artifactId>
  26. <optional>true</optional>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.webjars</groupId>
  30. <artifactId>jquery</artifactId>
  31. <version>2.2.4</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.webjars</groupId>
  35. <artifactId>bootstrap</artifactId>
  36. <version>3.3.7</version>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <!-- Package as an executable jar/war -->
  42. <plugin>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-maven-plugin</artifactId>
  45. </plugin>
  46. </plugins>
  47. </build>
  48. </project>

 

3. Spring REST API

3.1一个REST控制器,接受SearchCriteria并返回一个ResponseEntity

SearchController.java

  1. package com.mkyong.controller;
  2. import com.mkyong.model.AjaxResponseBody;
  3. import com.mkyong.model.SearchCriteria;
  4. import com.mkyong.model.User;
  5. import com.mkyong.services.UserService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.validation.Errors;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import javax.validation.Valid;
  13. import java.util.List;
  14. import java.util.stream.Collectors;
  15. @RestController
  16. public class SearchController {
  17. UserService userService;
  18. @Autowired
  19. public void setUserService(UserService userService) {
  20. this.userService = userService;
  21. }
  22. @PostMapping("/api/search")
  23. public ResponseEntity<?> getSearchResultViaAjax(
  24. @Valid @RequestBody SearchCriteria search, Errors errors) {
  25. AjaxResponseBody result = new AjaxResponseBody();
  26. //If error, just return a 400 bad request, along with the error message
  27. if (errors.hasErrors()) {
  28. result.setMsg(errors.getAllErrors()
  29. .stream().map(x -> x.getDefaultMessage())
  30. .collect(Collectors.joining(",")));
  31. return ResponseEntity.badRequest().body(result);
  32. }
  33. List<User> users = userService.findByUserNameOrEmail(search.getUsername());
  34. if (users.isEmpty()) {
  35. result.setMsg("no user found!");
  36. } else {
  37. result.setMsg("success");
  38. }
  39. result.setResult(users);
  40. return ResponseEntity.ok(result);
  41. }
  42. }

 

3.2一些POJO。

AjaxResponseBody.java

  1. package com.mkyong.model;
  2. import java.util.List;
  3. public class AjaxResponseBody {
  4. String msg;
  5. List<User> result;
  6. //getters and setters
  7. }

 

User.java

  1. package com.mkyong.model;
  2. public class User {
  3. String username;
  4. String password;
  5. String email;
  6. public User(String username, String password, String email) {
  7. this.username = username;
  8. this.password = password;
  9. this.email = email;
  10. }
  11. //getters and setters
  12. }

 

3.3验证。

SearchCriteria.java

  1. package com.mkyong.model;
  2. import org.hibernate.validator.constraints.NotBlank;
  3. public class SearchCriteria {
  4. @NotBlank(message = "username can't empty!")
  5. String username;
  6. public String getUsername() {
  7. return username;
  8. }
  9. public void setUsername(String username) {
  10. this.username = username;
  11. }
  12. }

 

3.4初始化某些用户进行搜索的服务。

UserService.java

  1. package com.mkyong.services;
  2. import com.mkyong.model.User;
  3. import org.springframework.stereotype.Service;
  4. import javax.annotation.PostConstruct;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.stream.Collectors;
  8. @Service
  9. public class UserService {
  10. private List<User> users;
  11. // Love Java 8
  12. public List<User> findByUserNameOrEmail(String username) {
  13. List<User> result = users.stream()
  14. .filter(x -> x.getUsername().equalsIgnoreCase(username))
  15. .collect(Collectors.toList());
  16. return result;
  17. }
  18. // Init some users for testing
  19. @PostConstruct
  20. private void iniDataForTesting() {
  21. users = new ArrayList<User>();
  22. User user1 = new User("mkyong", "password111", "mkyong@yahoo.com");
  23. User user2 = new User("yflow", "password222", "yflow@yahoo.com");
  24. User user3 = new User("laplap", "password333", "mkyong@yahoo.com");
  25. users.add(user1);
  26. users.add(user2);
  27. users.add(user3);
  28. }
  29. }

 

3.5 Spring Boot Starter。

UserService.java

  1. package com.mkyong;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class SpringBootWebApplication {
  6. public static void main(String[] args) throws Exception {
  7. SpringApplication.run(SpringBootWebApplication.class, args);
  8. }
  9. }

 

4. HTML表单+ jQuery Ajax

4.1一个简单的HTML表单,用bootstrap装饰。

ajax.html

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>Spring Boot ajax example</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  6. <link rel="stylesheet" type="text/css"
  7. href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
  8. </head>
  9. <body>
  10. <nav class="navbar navbar-inverse">
  11. <div class="container">
  12. <div class="navbar-header">
  13. <a class="navbar-brand" href="#">Mkyong.com</a>
  14. </div>
  15. </div>
  16. </nav>
  17. <div class="container" style="min-height: 500px">
  18. <div class="starter-template">
  19. <h1>Spring Boot AJAX Example</h1>
  20. <div id="feedback"></div>
  21. <form class="form-horizontal" id="search-form">
  22. <div class="form-group form-group-lg">
  23. <label class="col-sm-2 control-label">Username</label>
  24. <div class="col-sm-10">
  25. <input type="text" class="form-control" id="username"/>
  26. </div>
  27. </div>
  28. <div class="form-group">
  29. <div class="col-sm-offset-2 col-sm-10">
  30. <button type="submit" id="bth-search"
  31. class="btn btn-primary btn-lg">Search
  32. </button>
  33. </div>
  34. </div>
  35. </form>
  36. </div>
  37. </div>
  38. <div class="container">
  39. <footer>
  40. <p>
  41. © <a href="http://www.mkyong.com">Mkyong.com</a> 2017
  42. </p>
  43. </footer>
  44. </div>
  45. <script type="text/javascript"
  46. src="webjars/jquery/2.2.4/jquery.min.js"></script>
  47. <script type="text/javascript" src="js/main.js"></script>
  48. </body>
  49. </html>

 

4.2获取HTML表单,将搜索条件转换为JSON格式JSON.stringify,并通过发送POST请求jQuery.ajax

main.js

  1. $(document).ready(function () {
  2. $("#search-form").submit(function (event) {
  3. //stop submit the form, we will post it manually.
  4. event.preventDefault();
  5. fire_ajax_submit();
  6. });
  7. });
  8. function fire_ajax_submit() {
  9. var search = {}
  10. search["username"] = $("#username").val();
  11. $("#btn-search").prop("disabled", true);
  12. $.ajax({
  13. type: "POST",
  14. contentType: "application/json",
  15. url: "/api/search",
  16. data: JSON.stringify(search),
  17. dataType: 'json',
  18. cache: false,
  19. timeout: 600000,
  20. success: function (data) {
  21. var json = "<h4>Ajax Response</h4><pre>"
  22. + JSON.stringify(data, null, 4) + "</pre>";
  23. $('#feedback').html(json);
  24. console.log("SUCCESS : ", data);
  25. $("#btn-search").prop("disabled", false);
  26. },
  27. error: function (e) {
  28. var json = "<h4>Ajax Response</h4><pre>"
  29. + e.responseText + "</pre>";
  30. $('#feedback').html(json);
  31. console.log("ERROR : ", e);
  32. $("#btn-search").prop("disabled", false);
  33. }
  34. });
  35. }

 

完成。

5.演示

5.1启动Spring Boot

终奌站

  1. <span style="color:#212529"><span style="color:black"><code class="language-bash">$ mvn spring-boot:run
  2. <span style="color:#0077aa">.</span> ____ _ __ _ _
  3. /\\ / ___<span style="color:#669900">'_ __ _ _(_)_ __ __ _ \ \ \ \
  4. ( ( )\___ | '</span>_ <span style="color:#a67f59">|</span> <span style="color:#669900">'_| | '</span>_ \/ _` <span style="color:#a67f59">|</span> \ \ \ \
  5. \\/ ___<span style="color:#999999">)</span><span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span>_<span style="color:#999999">)</span><span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span> <span style="color:#a67f59">||</span> <span style="color:#999999">(</span>_<span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span> <span style="color:#999999">)</span> <span style="color:#999999">)</span> <span style="color:#999999">)</span> <span style="color:#999999">)</span>
  6. ' <span style="color:#a67f59">|</span>____<span style="color:#a67f59">|</span> .__<span style="color:#a67f59">|</span>_<span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span>_<span style="color:#a67f59">|</span>_<span style="color:#a67f59">|</span> <span style="color:#a67f59">|</span>_\__, <span style="color:#a67f59">|</span> / / / /
  7. <span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">=</span><span style="color:#a67f59">|</span>_<span style="color:#a67f59">|</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">==</span><span style="color:#a67f59">|</span>___/<span style="color:#a67f59">=</span>/_/_/_/
  8. :: Spring Boot :: <span style="color:#999999">(</span>v1.5.1.RELEASE<span style="color:#999999">)</span>
  9. 2017-02-03 14:56:36 DEBUG com.mkyong.SpringBootWebApplication - Running with Spring Boot v1.5.1.RELEASE, Spring v4.3.6.RELEASE
  10. 2017-02-03 14:56:36 INFO com.mkyong.SpringBootWebApplication - No active profile set, falling back to default profiles: default
  11. 2017-02-03 14:56:39 INFO com.mkyong.SpringBootWebApplication - Started SpringBootWebApplication <span style="color:#0077aa">in</span> 2.828 seconds <span style="color:#999999">(</span>JVM running <span style="color:#0077aa">for</span> 3.295<span style="color:#999999">)</span>
  12. </code></span></span>

 

5.2访问http:// localhost:8080 /

5.3如果用户名为空!

5.4如果找不到用户名!

5.5如果找到用户名!

6.下载源代码

下载 - spring-boot-ajax-example.zip(10 KB)

参考

  1. Spring IO - 构建RESTful Web服务
  2. MDN - JSON.stringify()
  3. Spring 4 MVC Ajax Hello World示例

关于作者

作者形象

mkyong

Mkyong.com的 创始人,喜欢Java和开源的东西。在Twitter上关注他,或在FacebookGoogle Plus上与他交朋友。如果您喜欢z这个的教程,请考虑向这些慈善机构捐款。[很赞]

本文翻译自:https://www.mkyong.com/spring-boot/spring-boot-ajax-example/

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/652114
推荐阅读
相关标签
  

闽ICP备14008679号