我有简单的功能:
$scope.addComment = function () {
var url = "";
url = "/" + contextPath + "/tickets/" + ticketId + "/comments/new";
var data = {comment: $scope.newComment};
$http.post(url, data)
.then(
function (response) {
var comments = response.data;
angular.forEach(comments, function (value, key) {
value.date = $filter('date')(value.date, "MMM dd, yyyy HH:mm");
});
$scope.comments = comments;
},
function (errResponse) {
console.log(errResponse.statusText);
}
)
}
和 Controller :
@RequestMapping(value = "/{ticketId}/comments/new", method = RequestMethod.POST)
public ResponseEntity<List<CommentDto>> addComments(@PathVariable int ticketId,
@RequestParam(value = "comment", required = false) String text,
HttpServletRequest request,
Authentication authentication) {
if (text == "" || text == null) {
return new ResponseEntity<>(getTicketComments(ticketId), HttpStatus.OK);
}
Comment newComment = new Comment();
User user = userService.loadUserByUsername(authentication.getName());
newComment.setUserId(user.getId());
newComment.setTicketId(ticketId);
newComment.setText(text);
commentService.save(newComment);
return new ResponseEntity<>(getTicketComments(ticketId), HttpStatus.OK);
所以我尝试通过两种方式获取参数“Comment”:通过@RequestParam,以及从请求对象,但是@Request param始终为null,并且来自请求对象的params映射始终为空。我做错了什么?
最佳答案
如下所示更改您的 Controller -
@RequestMapping(value = "/{ticketId}/comments/new", method = RequestMethod.POST)
public ResponseEntity<List<CommentDto>>
addComments(@PathVariable int ticketId,@RequestBody CommentsMapper comMapObj)
注意 - requestBody 添加了一个映射器类来映射您的评论,现在创建一个映射器类,如下所示
class CommentsMapper{
private String comments;
//Create getters and setters
}
现在您将能够在 Controller
中通过 comMapObj.getComment()
访问您的comment
如果您有多个注释,则使用 String[]
或您在映射器中需要的任何类型。
甚至您也可以使用Comment
(您的类(class))类型。
关于java - 无法从Spring Controller 中的http post正文读取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519405/