Spring MVC Ajax Post 400错误(错误请求)(Spring MVC Ajax Post 400 Error (Bad Request))

所以我正在使用Spring MVC并且我正在尝试做一个ajax帖子来向Post实体添加comment ,就像典型的社交网络一样。 我在Chrome开发者工具中遇到错误,该错误表示Failed to load resource: the server responded with a status of 400 (Bad Request) 。 我想这可能意味着我的控制器出了问题,但是这个设置的方式,它不是让我在调试模式下检查出来的。

我将向大家展示一起工作的所有代码片段,以便你们可以更好地理解我的问题。

所以这是我的Ajax,一切都在运行,并发送“有一个错误”的消息,所以它至少运行代码并到达控制器。

CDATA东西也是Thymeleaf。

<script th:inline="javascript"> /*<![CDATA[*/ var postById = /*[[${postById.id}]]*/'1'; var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); $(document).ready(function(){ $("#submit").on("click", function(ev) { ev.preventDefault(); $.ajax({ url : "newComment", type : "post", data : { "postById" : postById, "newComment" : $("#newComment").val() }, success : function(data) { console.log(data); location.reload(); }, error : function() { console.log("There was an error"); //location.reload(); } }); }); }); /*]]>*/ </script>

这是我的Controller Get方法

@RequestMapping(value="viewCourse/post/{postId}", method=RequestMethod.GET) public ModelAndView postViewGet (@RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "page", required = false) Integer page, @PathVariable Long postId) { ModelAndView modelAndView = new ModelAndView("post"); { // Evaluate page size. If requested parameter is null, return initial // page size int evalPageSize = pageSize == null ? INITIAL_PAGE_SIZE : pageSize; // Evaluate page. If requested parameter is null or less than 0 (to // prevent exception), return initial size. Otherwise, return value of // param. decreased by 1. int evalPage = (page == null || page < 1) ? INITIAL_PAGE : page - 1; //StudySet studySet = studySetRepo.findOne(studySetId); //List <Row> rows = studySet.getRows(); //Set<Row> rowSet = new TreeSet<Row>(rows); Post postById = postRepo.findOne(postId); Comment comment = new Comment(); Page<Comment> postComments = commentService.findByPostOrderByIdDesc((postById), new PageRequest(evalPage, evalPageSize)); Pager pager = new Pager(postComments.getTotalPages(), postComments.getNumber(), BUTTONS_TO_SHOW); modelAndView.addObject("postId", postId); modelAndView.addObject("postById", postById); modelAndView.addObject("postComments", postComments); modelAndView.addObject("comment", comment); modelAndView.addObject("selectedPageSize", evalPageSize); modelAndView.addObject("pageSizes", PAGE_SIZES); modelAndView.addObject("pager", pager); return modelAndView; } }

这是我的Controller Post方法

@RequestMapping(value="viewCourse/post/newComment", method=RequestMethod.POST) public @ResponseBody Post newComment (@Valid @RequestParam Long postId, @RequestParam String newComment, ModelMap model, @AuthenticationPrincipal User user) { Post post = postRepo.findOne(postId); Comment comment = new Comment(); comment.setComment(newComment); comment.setPost(post); comment.setDate(LocalDate.now()); comment.setTime(LocalTime.now()); comment.setDateTime(LocalDateTime.now()); comment.setUser(user); user.getComments().add(comment); post.getComments().add(comment); commentRepo.save(comment); Post savedPost = postRepo.save(post); return savedPost; }

此外,我在实体对象中有一些注释,可能与它有关。

这是我的用户实体

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true) @JsonManagedReference public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; }

这是我的评论实体

@ManyToOne @JsonBackReference public User getUser() { return user; } public void setUser(User user) { this.user = user; }

另外这里是Chrome开发者工具中我的控制台的图片,所以你们可以看到它给我的确切内容。

如果有人能够看到我出错的地方并指出我正确的方向,那将是非常好的,提前谢谢。

此外,如果你们需要看到任何其他代码,请告诉我。

So I'm using Spring MVC and I'm trying to do an ajax post to add a comment to a Post entity, like a typical social network. And I'm getting an error in the Chrome Developer's Tool's that says this Failed to load resource: the server responded with a status of 400 (Bad Request). I'm thinking that might mean something is going wrong in my controller, however the way this is set up, it's not letting me check it out in debug mode.

I'll show you guys all the pieces of code that work together so you guys can get a better understanding of my problem.

So here's my Ajax, and everything is running through, and sending a "there was an error" message, so It's at least running through the code and reaching the controller.

Also the CDATA stuff is for Thymeleaf.

<script th:inline="javascript"> /*<![CDATA[*/ var postById = /*[[${postById.id}]]*/'1'; var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); $(document).ready(function(){ $("#submit").on("click", function(ev) { ev.preventDefault(); $.ajax({ url : "newComment", type : "post", data : { "postById" : postById, "newComment" : $("#newComment").val() }, success : function(data) { console.log(data); location.reload(); }, error : function() { console.log("There was an error"); //location.reload(); } }); }); }); /*]]>*/ </script>

Here's my Controller Get Method

@RequestMapping(value="viewCourse/post/{postId}", method=RequestMethod.GET) public ModelAndView postViewGet (@RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "page", required = false) Integer page, @PathVariable Long postId) { ModelAndView modelAndView = new ModelAndView("post"); { // Evaluate page size. If requested parameter is null, return initial // page size int evalPageSize = pageSize == null ? INITIAL_PAGE_SIZE : pageSize; // Evaluate page. If requested parameter is null or less than 0 (to // prevent exception), return initial size. Otherwise, return value of // param. decreased by 1. int evalPage = (page == null || page < 1) ? INITIAL_PAGE : page - 1; //StudySet studySet = studySetRepo.findOne(studySetId); //List <Row> rows = studySet.getRows(); //Set<Row> rowSet = new TreeSet<Row>(rows); Post postById = postRepo.findOne(postId); Comment comment = new Comment(); Page<Comment> postComments = commentService.findByPostOrderByIdDesc((postById), new PageRequest(evalPage, evalPageSize)); Pager pager = new Pager(postComments.getTotalPages(), postComments.getNumber(), BUTTONS_TO_SHOW); modelAndView.addObject("postId", postId); modelAndView.addObject("postById", postById); modelAndView.addObject("postComments", postComments); modelAndView.addObject("comment", comment); modelAndView.addObject("selectedPageSize", evalPageSize); modelAndView.addObject("pageSizes", PAGE_SIZES); modelAndView.addObject("pager", pager); return modelAndView; } }

Here's my Controller Post Method

@RequestMapping(value="viewCourse/post/newComment", method=RequestMethod.POST) public @ResponseBody Post newComment (@Valid @RequestParam Long postId, @RequestParam String newComment, ModelMap model, @AuthenticationPrincipal User user) { Post post = postRepo.findOne(postId); Comment comment = new Comment(); comment.setComment(newComment); comment.setPost(post); comment.setDate(LocalDate.now()); comment.setTime(LocalTime.now()); comment.setDateTime(LocalDateTime.now()); comment.setUser(user); user.getComments().add(comment); post.getComments().add(comment); commentRepo.save(comment); Post savedPost = postRepo.save(post); return savedPost; }

Also I have some annotations in the entity objects, that could have something to do with it.

Here's my User Entity

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true) @JsonManagedReference public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; }

Here's my Comment entity

@ManyToOne @JsonBackReference public User getUser() { return user; } public void setUser(User user) { this.user = user; }

Also here's a picture of my console in the Chrome Developer Tools, so you guys can see exactly what it's showing me.

If anyone can see where I'm going wrong and point me in the right direction, that would be great, thanks in advance.

Also if you guys need to see any other code, just let me know.

最满意答案

我的问题是在Ajax中,我正在寻找postById.id ,当时我应该只使用我在控制器中的Get方法中添加到模型中的postId 。

My problem was in the Ajax, I was looking for the postById.id, when I should have been using just the postId that I added to the model in the Get method in the controller.

更多推荐