Fairy
Fairy

Reputation: 531

Can't read parameters from http post body in Spring Controller

I have simple function:

$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);
                }
            )
    }

And 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);

So I tried to get parameter 'Comment' in two ways: by @RequestParam, and from request object, but @Request param is always null and params map from request object is always empty. What am I doing wrong?

Upvotes: 0

Views: 1093

Answers (1)

Vipin CP
Vipin CP

Reputation: 3797

Change your controller as shown below -

     @RequestMapping(value = "/{ticketId}/comments/new", method = RequestMethod.POST)
        public ResponseEntity<List<CommentDto>> 
addComments(@PathVariable int ticketId,@RequestBody CommentsMapper comMapObj) 

Note - requestBody is added with a mapper class to map your comments , Now create a mapper class as below

class CommentsMapper{

private String comments;

//Create getters and setters

}

Now you will be able to access your comment in Controller as comMapObj.getComment() If you have multiple comments then use String[] or what ever type you need in mapper.

Even you can use Comment (Your class) type as well .

Upvotes: 1

Related Questions