[英]How to transfer data from HTML to controller Spring
我使用Spring Boot。 我没有web.xml和jsp文件
我有一个控制器来处理数据并将其写入数据库。
@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的帮助下检查了控制器的工作原理。
我有一个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>
如何将数据从页面传输到控制器?
谢谢您的帮助
这取决于您使用什么来在客户端(浏览器)和服务器之间进行调用,我将通过使用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
}
});
}
安杰洛
提交表单时,将收集表单数据。 它获取所有输入控件-输入,文本区域,选择,复选框等,并发送所有输入的内容。
如果您按提交按钮,则必须发送数据。 表单的操作是/logout
但是控制器希望/registration
更改操作。
还要检查RegistrationDto
是否具有电子邮件和密码字段来获取发送的数据。
正如评论中提到的@Zorglube一样,尝试仅删除consumes
并且还应验证表单具有属性th:object =“ registration”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.