0
我一直在使用AJAX和Spring MVC在我application.When用戶點擊註冊按鈕,下面的代碼在我叫UserController的控制器類工作:阿賈克斯POST請求的Spring MVC
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public ModelAndView registrationPage() {
ModelAndView model = new ModelAndView();
model.setViewName("registration");
return model;
}
註冊頁面(註冊。 jsp)包含一個表單。我在這個頁面中使用了ajax請求。 下面是jquery的Ajax代碼:
function ajaxPostForUsername() {
var contextPath = "<%= request.getContextPath()%>";
var username = $('#userName').val();
$.ajax({
type: 'POST',
url: contextPath + "/registration",
data: {username: username},
dataType: 'json',
contentType : "application/json",
success: function(response) {
console.log(response);
if (response == "USER_EXIST") {
$('.username-message').html("Username is exist.Please enter another!").css('color', 'red')
}
else {
$('.username-message').html("Valid username").css('color', 'green');
}
}
})
}
和使用的形式是:
<input type="text" id="userName" name="userName" placeholder="User Name" onblur="ajaxPostForUsername()" class="form-control" autofocus>
在稱爲控制器這個RegistrationController:
@RequestMapping(value = "/registration", method = RequestMethod.POST)
@ResponseBody
public String validateUsername(@RequestBody String username) {
String jsonData = "USER_NOT_EXIST";
if (userService.isUsernameExist(username)) {
jsonData = "USER_EXIST";
}
return jsonData;
}
像這個。我在pom.xml中添加依賴傑克遜:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.4</version>
</dependency>
所以,當我寫在用戶名字段的名稱,響應是:
HTTP Status 405 - Request method 'POST' not supported
和Java控制檯顯示:
WARNING: Handler execution resulted in exception: Request method 'POST' not supported.
它看起來像請求在圖片中看到的一樣正確。 Request-Response
我有搜索,但無法解決它。所以任何人都可以告訴我什麼是問題? (PS:我一直在使用Spring Security的,在我的形式<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
加入這個)