java - 无法从Spring Controller 中的http post正文读取参数

标签 java angularjs spring

我有简单的功能:

$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/

相关文章:

javascript - Angular js,从服务传递对象

java - 扩展 `JpaRepository` ,但仅实现子接口(interface)

java - 防止 gradle.properties 扩展

java - 如何在上下文初始化后创建 session bean

java - 错误不兼容的类型。后缀评估

java - 使用 hibernate 时出现意外行为

java - 在 Java API for WebSocket 1.0 中,Decoder#willDecode 真的是可选的吗?

java - 重新创建没有依赖项的 GitHub 项目 (Java)

javascript - 如何在 AngularJS 中使用 jqLit​​e 的方法

javascript - 没有数据绑定(bind)的渲染值