gpt4 book ai didi

java - 如何将数据从 HTML 传输到 Spring Controller

转载 作者:行者123 更新时间:2023-12-02 13:22:49 25 4
gpt4 key购买 nike

我使用 Spring Boot。我没有 web.xml 和 jsp 文件

我有一个 Controller 来处理数据并将其写入数据库。

@RequestMapping(value = "/registration", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Registration user", response = Account.class)
public AccountDto registration(@Valid @RequestBody RegistrationDto registration, HttpServletResponse response) {
Account account = new Account(registration.getEmail(), registration.getPassword());
return new AccountDto(account);
}

我在 Swagger 的帮助下检查了 Controller ,它是否有效。

我有一个 HTML 页面,用户可以在其中输入数据。

<body>
<h1 th:inline="text">Please register</h1>

<form th:action="@{/logout}" method="post">
<div>
<label>
E-mail:<input type="email" name="email"/>
Password:<input type="password" name="password"/>
</label>
</div>
<input type="submit" name="registration" value="Registration"/>
</form>
</body>

如何将数据从页面传输到 Controller ?

感谢您的帮助

最佳答案

这取决于您使用什么来在客户端(浏览器)和服务器之间进行调用我将通过使用 JQuery 并执行类似的操作来使用 AJAX 调用

var dataObj = new Object();
dataObj.email = $("#email").val();
dataObj.password = $("#passord").val();

$.ajax({
url : '/registration',
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
type : 'POST',
data: JSON.stringify(dataObj),
beforeSend : function(){
//do something before send (e.g. show a message like: please wait)
});

},
complete : function(){
//do something after sent (e.g. remove the message please wait)
},
success : function(data) {
//handle the success response
},
error : function(data) {
//handle the error response
}
});

希望有用

安杰洛

编辑

为了提交数据,您可以通过这种方式添加一个监听器来提交(始终使用 JQuery)

//This is called after the DOM is fully loaded
$(function() {
$("#mySubmitId").click(function(evt){
//Prevent the default submit
evt.preventDefault();
//call the submit funtion
submitData();
});
});

function submitData()
{
var dataObj = new Object();
dataObj.email = $("#email").val();
dataObj.password = $("#passord").val();

$.ajax({
url : '/registration',
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
type : 'POST',
data: JSON.stringify(dataObj),
beforeSend : function(){
//do something before send (e.g. show a message like: please wait)
});

},
complete : function(){
//do something after sent (e.g. remove the message please wait)
},
success : function(data) {
//handle the success response
},
error : function(data) {
//handle the error response
}
});
}

安杰洛

关于java - 如何将数据从 HTML 传输到 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com