Я делаю небольшое веб-приложение, чтобы применить то, что я узнал из Spring boot и ajax.
У меня есть веб-страница, на которой у меня есть форма с двумя входами даты: «дата начала» и «дата окончания». Я хотел отправить ввод пользователя в RestController и получить ответ, который я должен показать в пустом div.
вот что я делал до сих пор
Моя форма:
<div class = "w3-container w3-padding-64" id = "reserver_salle">
<h1>Resrvation de salle</h1><br>
<form id = "reserver_salle_form" >
<p><input class = "w3-input w3-padding-16" id = "dateDebut" type = "date" required placeholder = "Date début"></p>
<p><input class = "w3-input w3-padding-16" id = "dateFin" type = "date" required placeholder = "Date fin"></p>
<p><button id = "searchSalle" type = "submit" class = "w3-button w3-light-grey w3-section" >[[#{homePage.envoyer}]]</button></p>
</form>
</div>
<div id = "salleList" class = "w3-container">
</div>
<script type = "text/javascript" th:src = "@{~/cdnjs.cloudflare.com_ajax_libs_jquery_2.1.3_jquery.min.js}">
</script>
<script type = "text/javascript" th:src = "@{~/js/start_page.js}"></script>
Сейчас я покажу вам свой ajax-скрипт
$(document).ready(function () {
//alert("is loading");
$("#searchSalle").submit(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_serach_salle();
});
$("#send_mail").submit(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_send_mail();
});
});
function fire_serach_salle(){
var searchReserv = {};
searchReserv["dateDebutAnnee"] = $("#dateDebut").val().split('-')[0];
searchReserv["dateDebutMois"] = $("#dateDebut").val().split('-')[1];
searchReserv["dateDebutJour"] = $("#dateDebut").val().split('-')[2];
searchReserv["dateFinAnnee"] = $("#dateFin").val().split('-')[0];
searchReserv["dateFinMois"] = $("#dateFin").val().split('-')[1];
searchReserv["dateFinJour"] = $("#dateFin").val().split('-')[2];
$("#searchSalle").prop("disabled",true);
console.info(searchReserv);
$.ajax({
type: "POST",
contentType: "application/json",
url: "/homePage/reservation/search",
data: JSON.stringify(searchReserv),
dataType: 'json',
cache: false,
timeout: 900000,
success: function (result) {
if (result.answer === "DONE") {
/*<![CDATA[*/
var html ='<h2>Liste des salles </h2>';
html+='<ul class = "w3-ul w3-hoverable">';
for(var i = 0 ;i<result.data.length;i++){
html += ' <li class = "w3-display-container ">'+result.data[i].titre+'-'+result.data[i].id+'<span onclick = "reserve('+result.data[i].id+')" class = "w3-button w3-transparent w3-display-right w3-hover-green">reserver</span></li>';
}
html+='</ul>';
/*]]>*/
$("#salleList").html(html);
$("#searchSalle").prop("disabled",false);
}
}
});
}
сейчас я покажу свой контроллер
@RestController
@PropertySource(ignoreResourceNotFound = true, value = "classpath:messages.properties")
public class HomePageController {
@RequestMapping(value = "/homePage/reservation/search", method = RequestMethod.POST)
public @ResponseBody
AjaxResponse doSearch(@RequestBody SearchReserv searchReserv, Model model) {
try {
System.out.println(searchReserv);
ArrayList<ReservationSearchResponse> response = new ArrayList<>();
response.add(new ReservationSearchResponse(Long.valueOf(0), "hello 0"));
response.add(new ReservationSearchResponse(Long.valueOf(1), "hello 1"));
return new AjaxResponse("DONE", response);
} catch (Exception e) {
e.printStackTrace();
return new AjaxResponse("BAD", null);
}
}
Наконец, мои два класса AjaxResponse и SearcheReserv
public class AjaxResponse {
private String answer;
private Object data;
//geters setters and contructors
}
import org.springframework.stereotype.Component;
/**
*
* @author taleb
*/
@Component
public class SearchReserv {
private int dateDebutAnnee;
private int dateDebutMois;
private int dateDebutJour;
private int dateFinAnnee;
private int dateFinMois;
private int dateFinJour;
//geters setters and contructors
}
То, что я не могу понять, я использую этот способ для реализации отправки почты с помощью весенней почты, и он отлично работает
но в этом я все еще получаю
There was an unexpected error (type=Method Not Allowed, status=405). Request method 'GET' not supported
в моем коде нет GET
Я использую последнюю версию Spring Boot 2.0.0.M7 У меня нет ручной настройки на сервере apache





Попробуйте использовать аннотацию @RequestMapping (метод = ПОЛУЧИТЬ) и после этого поделитесь результатом. Это должно решить эту проблему.
После нескольких часов работы проблема была глупой. При прикреплении запроса Ajax мы делаем это с идентификатором формы, а не с кнопкой
Я исправил это, обновив свой сценарий ajax с
$("#searchSalle").submit(function (event)
к
$("#reserver_salle_form").submit(function (event)
и это работает как шарм