我有简单的应用程序AngularJS和Spring启动。我想将用户预填的整个表单传递给我的应用程序并注册。通常我没有问题 - 正在通过正确的结构和presto传递JSON obj。但是在这里我只是在cricle中运行。 表单有效负载发送到控制器,地址映射是正确的,但java表单内容为空
发送到服务器的有效负载:
{"userform":{"name":"a","surname":"a","email":"a@a.com","password":"a","confirmPassword":"a"}}
这是我的HTML:
<div class="alert alert-danger" ng-show="error">
There was a problem registering. Please try again.
</div>
<form role="form" name="userForm" ng-submit="register()">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" ng-model="formData.name"/>
</div>
<div class="form-group">
<label for="name">Surname:</label>
<input type="text" class="form-control" id="surname" name="surname" ng-model="formData.surname"/>
</div>
<div class="form-group">
<label for="name">Email:</label>
<input type="text" class="form-control" id="email" name="email" ng-model="formData.email"/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" ng-model="formData.password"/>
</div>
<div class="form-group">
<label for="confirmpassword">Password:</label>
<input type="password" class="form-control" id="confirmpassword" name="confirmpassword"
ng-model="formData.confirmpassword"/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
这里是java脚本
app.controller('register', function ($scope, $rootScope, $http) {
$scope.formData = {};
$scope.register = function () {
$http.post('/api/register', {userform: $scope.formData}).then(
function (resposne) {
console.log("registered");
console.log(response);
},
function (response) {
console.log("Register error")
}
)
}
});
在这里控制器:
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@RequestBody RegisterForm userform) {
System.out.println("name:" + userform.getName());
System.out.println("surname:" + userform.getSurname());
return "OK";
}
}
最后但并非最不重要的RegisterForm:
public class RegisterForm {
private static final String NOT_BLANK_MESSAGE = "Cannot be blank";
@NotBlank
@Email(message = "Not email")
private String email;
@NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
private String name;
@NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
private String surname;
@NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
private String password;
@NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
private String confirmpassword;
/*-----GETTERS AND SETTERS HERE----*/
}
答案 0 :(得分:1)
你需要发送这样的请求
$http.post('/api/register', $scope.formData)
然后Spring将能够将您的请求映射到RegisterForm pojo。
在您的代码中,Spring尝试将您的请求映射到具有RegisterForm类型的一个字段userform
的类。