Автор оригинала: mkyong.
В этой статье будет показано, как использовать jQuery.ajax для отправки запроса HTML-формы в Spring REST API и возврата ответа JSON.
Используемые инструменты:
- Пружинный ботинок 1.5.1. ВЫПУСК
- Пружина 4.3.6. ВЫПУСК
- Мавен 3
- jQuery (запрос)
- Начальная загрузка 3
1. Структура проекта
Стандартная структура проекта Maven.
2. Зависимость от проекта
Обычная зависимость от загрузки Spring и некоторые веб-сайты ресурсы.
4.0.0 com.mkyong spring-boot-ajax-example jar 1.0 org.springframework.boot spring-boot-starter-parent 1.5.1.RELEASE 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools true org.webjars jquery 2.2.4 org.webjars bootstrap 3.3.7 org.springframework.boot spring-boot-maven-plugin
3. API весеннего ОТДЫХА
3.1 Контроллер REST, принимает Критерии поиска и возвращает Отзывчивость
package com.mkyong.controller;
import com.mkyong.model.AjaxResponseBody;
import com.mkyong.model.SearchCriteria;
import com.mkyong.model.User;
import com.mkyong.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 users = userService.findByUserNameOrEmail(search.getUsername());
if (users.isEmpty()) {
result.setMsg("no user found!");
} else {
result.setMsg("success");
}
result.setResult(users);
return ResponseEntity.ok(result);
}
}
3.2 Немного POJO.
package com.mkyong.model;
import java.util.List;
public class AjaxResponseBody {
String msg;
List result;
//getters and setters
}
package com.mkyong.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;
}
//getters and setters
}
3.3 Проверка.
package com.mkyong.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;
}
}
3.4 Сервис для инициализации некоторых пользователей для поиска.
package com.mkyong.services;
import com.mkyong.model.User;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@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("mkyong", "password111", "mkyong@yahoo.com");
User user2 = new User("yflow", "password222", "yflow@yahoo.com");
User user3 = new User("laplap", "password333", "mkyong@yahoo.com");
users.add(user1);
users.add(user2);
users.add(user3);
}
}
3.5 Пружинный Загрузочный Стартер.
package com.mkyong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
4. HTML-форма + jQuery Ajax
4.1 Простая HTML-форма, оформленная с помощью bootstrap.
Spring Boot ajax example
Spring Boot AJAX Example
4.2 Получить HTML-форму, преобразовать критерии поиска в формат JSON с помощью JSON.stringify и отправить запрос POST с помощью jQuery.ajax
$(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();
$("#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 = "Ajax Response
"
+ e.responseText + "";
$('#feedback').html(json);
console.log("ERROR : ", e);
$("#btn-search").prop("disabled", false);
}
});
}
Сделано.
5. ДЕМОНСТРАЦИЯ
5.1 Запуск Пружинной Загрузки
$ mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.1.RELEASE) 2017-02-03 14:56:36 DEBUG com.mkyong.SpringBootWebApplication - Running with Spring Boot v1.5.1.RELEASE, Spring v4.3.6.RELEASE 2017-02-03 14:56:36 INFO com.mkyong.SpringBootWebApplication - No active profile set, falling back to default profiles: default 2017-02-03 14:56:39 INFO com.mkyong.SpringBootWebApplication - Started SpringBootWebApplication in 2.828 seconds (JVM running for 3.295)
5.2 Доступ http://localhost:8080/
5.3 Если имя пользователя пустое!
5.4 Если имя пользователя не найдено!
5.5 Если имя пользователя найдено!
6. Скачать Исходный Код
Рекомендации
Оригинал: “https://mkyong.com/spring-boot/spring-boot-ajax-example/”