这篇博文主要用于新手学习Spring Boot,同时也记录自己学习的过程…
文章内容主要来源于易百教程
本文将展示如何使用jQuery.ajax将HTML表单请求发送到Spring REST API并返回JSON响应。
使用的工具:
1.项目结构
创建一个标准的Maven项目:spring-boot-ajax-example,用于演示在Spring Boot中使用Ajax技术,搜索用户信息。其结构如下图所示-
2.项目依赖
文件:pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.thgroupId>
<artifactId>spring-boot-ajax-exampleartifactId>
<packaging>jarpackaging>
<version>1.0version>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.3.RELEASEversion>
parent>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>bootstrapartifactId>
<version>3.3.7version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>springbootfinalName>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-war-pluginartifactId>
<configuration>
<warSourceExcludes>src/main/resources/**warSourceExcludes>
<warName>springbootwarName>
configuration>
plugin>
plugins>
build>
project>
3.Spring REST API
REST控制器,接受一个SearchCriteria并返回一个ResponseEntity。
一个正常的Spring Boot依赖和一些webjars资源。文件:SearchController.java如下所示-
package com.th.controller;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
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 com.th.model.AjaxResponseBody;
import com.th.model.SearchCriteria;
import com.th.model.User;
import com.th.service.UserService;
@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 (errors.hasErrors()) {
result.setMsg(
errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(",")));
return ResponseEntity.badRequest().body(result);
}
List 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
package com.th.model;
import java.util.List;
public class AjaxResponseBody {
private String msg;
private List result;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List getResult() {
return result;
}
public void setResult(List result) {
this.result = result;
}
}
文件:User.java
package com.th.model;
public class User {
private String username;
private String password;
private String email;
public User(String username, String password, String email) {
super();
this.username = username;
this.password = password;
this.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;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", email=" + email + "]";
}
}
验证器类:SearchCriteria.java
package com.th.model;
import javax.validation.constraints.NotBlank;
public class SearchCriteria {
@NotBlank(message = "username can't empty!")
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
用于初始化一些用户进行搜索的服务。文件:UserService.java 所下所示-
package com.th.service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import com.th.model.User;
@Service
public class UserService {
private List users;
// Love Java 8
public List findByUserNameOrEmail(String username) {
List result = users.stream().filter(x -> x.getUsername().equalsIgnoreCase(username)).collect(Collectors.toList());
return result;
}
// Init some users for testing
@PostConstruct
private void iniDataForTesting() {
users = new ArrayList();
User user1 = new User("maxsu", "password111", "[email protected]");
User user2 = new User("yiflow", "password222", "[email protected]");
User user3 = new User("minaxu", "password333", "[email protected]");
User user4 = new User("minalee", "password333", "[email protected]");
User user5 = new User("yiiflow", "password333", "[email protected]");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
}
}
Spring Boot启动器(程序入口),参考一下代码实现。文件:SpringBootWebApplication.java如下所示-
package com.th;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
4.HTML表单+jQuery Ajax
一个简单的HTML表单,用bootstrap框架装饰。
文件:index.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Ajax实例title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Spring Boota>
div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Homea>li>
<li><a href="#about">Abouta>li>
ul>
div>
div>
nav>
<div class="container" style="min-height: 500px">
<div class="starter-template">
<h1>Spring Boot AJAX 示例h1>
<div id="feedback">div>
<form class="form-horizontal" id="search-form">
<div class="form-group form-group-lg">
<label class="col-sm-2 control-label">用户名:label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username"/>
div>
div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="bth-search"
class="btn btn-primary btn-lg">搜索
button>
div>
div>
form>
div>
div>
<script type="text/javascript"
src="js/jquery.min.js">script>
<script type="text/javascript" src="js/main.js">script>
body>
html>
获取HTML表单,并通过JSON.stringify将搜索条件转换为JSON格式,并通过jQuery.ajax发送POST请求。
文件:main.js 所下所示-
$(document).ready(function () {
$("#search-form").submit(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
var search = {}
search["username"] = $("#username").val();
//search["email"] = $("#email").val();
$("#btn-search").prop("disabled", true);
$.ajax({
type: "POST",
contentType: "application/json",
url: "/api/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
var json = "Ajax Response
"
+ JSON.stringify(data, null, 4) + "
";
$('#feedback').html(json);
console.log("SUCCESS : ", data);
$("#btn-search").prop("disabled", false);
},
error: function (e) {
var json = ""+ e.responseText + ""; $('#feedback').html(json); console.log("ERROR : ", e); $("#btn-search").prop("disabled", false); } }); }
5.运行示例
打开浏览器,访问以下地址:http://localhost:8080/ , 应该会看到如下页面 -
如果没有输入用户名,直接点击“搜索”,那么应该会看到以下结果 -
如果输入一个存在的用户名:maxsu,直接点击“搜索”,那么应该会看到以下结果 -
相关文章: