Spring MVC 400 错误请求 Ajax

2023-11-29

我一直在 Ajax 请求上收到 400 Bad Request。我不知道这会出什么问题。我在用着:

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version> 
</dependency> 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
<version>4.0.5.RELEASE</version> </dependency>

控制器:

@Controller("bookController")
@RequestMapping("/book")
public class BookControllerImpl implements BookController {

    @Autowired
    BookService bookService;

    @Override
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String addBookToSystem(Model model) {
        model.addAttribute("book", new Book());
        return "book/newBook";
    }

    @Override
    @RequestMapping(value = "/new", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Book addBookToSystem(@RequestBody Book book) {
        book.setBookStatus(BookStatus.AWAITING);
        return bookService.get(bookService.save(book));
    }

阿贾克斯调用:

$(document).ready(function(){

    $('#addBook').submit(function(event) {

        var ISBN = $('#ISBN').val();
        var author = $('#author').val();
        var description = $('#description').val();
        var pages = $('#pages').val();
        var publicationYear = $('#publicationYear').val();
        var publisher = $('#publisher').val();
        var title = $('#title').val();
        var json = { "ISBN" : ISBN, "author" : author, "description" : description, "pages" : pages, "publicationYear" : publicationYear, "publisher" : publisher, "title" : title };

        $.ajax({
            url: $("#addBook").attr("action"),
            data: JSON.stringify(json),
            type: "POST",
            dataType: 'json',
            contentType: 'application/json',
            success: function(book) {
                var respContent = "";

                respContent += "<span class='success'>Dodano ";
                respContent += book.title;
                respContent += " do listy ksiazek oczekujacych na zatwierdzenie!</span>";

                $("#bookResponse").html(respContent);
            }
        });
        event.preventDefault();
    });
});

HTTP 请求:

POST /ksiazka/book/new.json HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 100
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: application/json
Referer: http://localhost:8080/ksiazka/book/new
Accept-Encoding: gzip,deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4,pt;q=0.2
Cookie: SPRING_SECURITY_REMEMBER_ME_COOKIE=bWFjaWVqbWlzMkBnbWFpbC5jb206MTQxNzUzODc3ODU4NjpjYjY3YTZiMWYyMGJjODYyMDYxMDQyNDIyN2NmNjQ3Mg; JSESSIONID=c5a72acb3bd1a165f9c2d705a199

回复:

HTTP/1.1 400 Bad Request
Server: GlassFish Server Open Source Edition  4.1
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  4.1  Java/Oracle Corporation/1.8)
Content-Language: 
Content-Type: text/html
Date: Tue, 04 Nov 2014 19:49:08 GMT
Connection: close
Content-Length: 1105

有什么想法如何解决这个问题吗? 作为我使用的基础this教程。我搜索并阅读了大多数带有 400 Bad Request 错误的线程,但这并没有解决我的问题。

编辑: 图书类别:

    @Entity
    @Table(name="Book")
    @Indexed
    public class Book {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "bookId")
        private Long id;
        @Column(nullable = false)
        @Field(index = Index.YES, analyze=Analyze.YES, store=Store.NO)
        private String title;
        @Column(nullable = false, unique = true)
        private String ISBN;
        @Column(nullable = false)
        @Field(index = Index.YES, analyze=Analyze.YES, store=Store.NO)
        private String author;
        private String publisher;
        @Column(length = 1000)
        private String description;
        private int publicationYear;
        private int pages;
        @Enumerated(EnumType.STRING)
        @Column(nullable = false)
        private BookStatus bookStatus;
        @ManyToMany(mappedBy = "booksWant", cascade = CascadeType.ALL)
        private List<User> user = new ArrayList<User>(0);
        @OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
        private List<UserBook> bookList = new ArrayList<UserBook>(0);

        public Book(String title, String ISBN, String author, String publisher, String description,
                    int publicationYear, int pages, BookStatus bookStatus) {
            this.title = title;
            this.ISBN = ISBN;
            this.author = author;
            this.publisher = publisher;
            this.description = description;
            this.publicationYear = publicationYear;
            this.pages = pages;
            this.bookStatus = bookStatus;
        }
   getters and setters

    }

Edit2:

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<tiles:insertDefinition name="template">
    <tiles:putAttribute name="content">

        <h2>book/newBook.jsp</h2>

        <div id="bookResponse">

        </div>
        <div>
            Add a book to system:
        </div>
        <div>
            <sf:form id="addBook" action="${pageContext.request.contextPath}/book/new" modelAttribute="book">
                <table>
                    <tr>
                        <td><label>isbn: </label></td>
                        <td><sf:input path="ISBN" id="ISBN" /></td>
                        <td><sf:errors path="ISBN" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Autor: </label></td>
                        <td><sf:input path="author" id="author" /></td>
                        <td><sf:errors path="author" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Tytul: </label></td>
                        <td><sf:input path="title" id="title" /></td>
                        <td><sf:errors path="title" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Opis: </label></td>
                        <td><sf:textarea path="description" id="description" /></td>
                        <td><sf:errors path="description" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Ilosc stron: </label></td>
                        <td><sf:input path="pages" id="pages" /></td>
                        <td><sf:errors path="pages" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Rok wydawania: </label></td>
                        <td><sf:input path="publicationYear" id="publicationYear" /></td>
                        <td><sf:errors path="publicationYear" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Wydawca: </label></td>
                        <td><sf:textarea path="publisher" id="publisher" /></td>
                        <td><sf:errors path="publisher" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><input name="submit" type="submit" value="Dodaj" class="btn btn-primary" /></td>
                    </tr>
                </table>
            </sf:form>
        </div>

    </tiles:putAttribute>
</tiles:insertDefinition>

我解决了我的问题。为了让它发挥作用,我做了以下事情: 首先我将依赖项更改为 jackson2

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.4.3</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

然后我用 @JsonProperty 和 @JsonIgnore 注释了我的 Book 类。这是我更新的 Book 类

 @Entity
    @Table(name="Book")
    @Indexed
    public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "bookId")
    @JsonIgnore
    private Long id;
    @Column(nullable = false)
    @Field(index = Index.YES, analyze=Analyze.YES, store=Store.NO)
    @JsonProperty("title")
    private String title;
    @Column(nullable = false, unique = true)
    @JsonProperty("ISBN")
    private String ISBN;
    @Column(nullable = false)
    @Field(index = Index.YES, analyze=Analyze.YES, store=Store.NO)
    @JsonProperty("author")
    private String author;
    @JsonProperty("publisher")
    private String publisher;
    @Column(length = 1000)
    @JsonProperty("description")
    private String description;
    @JsonProperty("publicationYear")
    private int publicationYear;
    @JsonProperty("pages")
    private int pages;
    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    @JsonIgnore
    private BookStatus bookStatus;
    @ManyToMany(mappedBy = "booksWant", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<User> user = new ArrayList<User>(0);
    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<UserBook> bookList = new ArrayList<UserBook>(0);

    public Book(String title, String ISBN, String author, String publisher, String description,
                int publicationYear, int pages, BookStatus bookStatus) {
        this.title = title;
        this.ISBN = ISBN;
        this.author = author;
        this.publisher = publisher;
        this.description = description;
        this.publicationYear = publicationYear;
        this.pages = pages;
        this.bookStatus = bookStatus;
    }
     getters and setters

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring MVC 400 错误请求 Ajax 的相关文章

随机推荐

  • 如何在 SceneKit 中使用着色器添加透明度?

    我想从图像中获得透明效果 现在我只是用圆环进行测试 但着色器似乎不适用于 alpha 据我从这个帖子中了解到的 在 Scenekit 中使用混合函数 以及这个关于透明度的维基链接 http en wikibooks org wiki GLS
  • 如何将dojo工具包与rails 3.1 asset pipeline和coffeescript一起使用?

    我正在尝试在 Rails 3 1 应用程序上使用 dojo toolkit 作为 JS 框架 但我正在努力将 dojo require 结构与 sprockets require 和 Coffeescript 结合起来 看起来dojo需要磁
  • 如何使用 netbeans 在 java 中每次掷骰子后询问用户是否愿意继续游戏?

    我需要帮助解决这个问题 掷骰子游戏是用两个六面骰子进行的 玩游戏的用户将掷两个骰子 并生成两个介于 1 到 6 之间的随机数 两个数字的总和将用于决定下一步 如果总和为 2 3 或 12 则玩家获胜 如果总和是 7 或 11 那么他 她就输
  • 关闭 SKScene 返回 UIKit 菜单

    一旦我的 SpriteKit 游戏结束 我想回到我的UIKit MenuViewController 根据我到目前为止所学到的 使用协议 委托是最好的 选项 但我无法让它发挥作用 我知道该协议可能会高于类声明GameViewControll
  • 运行 Fiddler 作为 HTTP 到 HTTPS 反向代理

    我的机器上正在运行一项服务 该服务在 HTTPS 上发布 在 HTTP 上启动似乎有点复杂 某个远程计算机通过 HTTP 对我的计算机执行调用 这不受我的控制 我想对我的服务执行一些非性能关键的测试 看起来最简单的方法是使用有点像 HTTP
  • 在 Fortran 的 SYSTEM 子例程中使用变量

    如何在执行的命令中使用变量system子程序调用 例如 如果我想创建多个目录 例如test 1 1 test 1 2 依此类推 直到test 3 3那么我的代码应该是什么 我正在尝试以下代码 但似乎无法弄清楚在 部分要写什么 integer
  • Git 错误:无法提交配置文件

    我正在尝试将新的远程存储库 GitHub 添加到现有项目 但遇到了一个我以前从未见过且不理解的错误 git remote add github email protected me myrepo git error could not co
  • 标头和 Selenium Webdriver 2

    有没有办法在 Selenium WebDriver 测试中添加标头 与 Firefox 修改标头插件一样 我无法使用 HtmlUnitDriver 因为浏览器必须可见 WebDriver 不允许您使用任何基于浏览器的驱动程序更改或设置标头
  • 如何在设计时禁用子控件?

    我有自己的控制权 源自TCustomPanel 它有一个孩子 TEdit 在上面 type TMyControl class TCustomPanel private FEditor TEdit public constructor Cre
  • 从字典创建类实例属性?

    我正在从 CSV 导入并大致以以下格式获取数据 Field1 3000 Field2 6000 RandomField 5000 字段的名称是动态的 嗯 它们是动态的 因为可能不止 Field1 和 Field2 但我知道Field1 an
  • 如何将 EntityFramework、Repository、UnitOfWork 和 Automapper 结合到一个 MVC 应用程序中?

    首先我决定创建一个名为它的接口IDataAccessLayer并开始将所有内容放入其中 类似的方法GetUsers GetUser int id GetOrderByNumber int number DeleteOrder int Id
  • 为什么要在instanceOf之后进行强制转换?

    在下面的例子中 来自我的课程包 我们想要给Square实例c1其他对象的引用p1 但前提是这两个类型是兼容的 if p1 instanceof Square c1 Square p1 我在这里不明白的是我们首先检查p1确实是一个Square
  • 以编程方式设置 Mozilla Firefox 的默认主页?

    我知道如何设置 Google Chrome 和 Internet Explorer 的默认主页 但我在 Google 和 Stackoverflow 上搜索了如何使用 Mozilla Firefox 实现此目的的可能答案 但没有机会 我想知
  • 有没有相当于mySQL的IN的php?

    在 mySQL 中编写 select 语句时 如果我想提取列值等于多个值之一的记录 我可以这样说 SELECT FROM myTable WHERE myColumn IN 1 5 7 在 PHP 中使用 OR 完成类似任务的唯一方法是吗
  • 推送通知 - 捕捉它们?

    好吧 这就是交易 我的应用程序正在使用 iOS 通知 在应用程序委托中 如果应用程序位于 我会在 didReceiveRemoteNotification 中捕获它们前景如果应用程序在 我会在 didBecomeActive 中捕获它背景我
  • Android 模拟器看不到,如何移动它?

    我在笔记本电脑上使用了一个额外的显示器 并将 Android 模拟器移到了那里 即使不再连接显示器 它似乎也会记住该位置 有什么方法可以重置窗口的位置 使其再次可见吗 您可以使用此方法来移动 Windows 环境中屏幕外的任何窗口 首先通过
  • 每个 App Engine 应用程序允许使用 3,000 个文件(而不是 1,000 个),这是否正确?

    根据这篇维基百科文章 每个应用程序允许 3 000 个文件 但我在 Google Groups 上读到一个帖子 有人的 Java 应用程序在尝试上传超过 1 000 个文件时收到警告 他通过将一些文件捆绑在 jar 中来解决这个问题 哪个是
  • 使用 Dir 按文件系统顺序从文件夹返回文件

    PixPath 是 jpg 文件夹的完整路径 我使用如下代码来处理每个 jpg fileName Dir PixPath Do Until fileName If Right fileName 4 jpg Then fileName Dir
  • 如何通过 LINQ 展平树?

    所以我有简单的树 class MyNode public MyNode Parent public IEnumerable
  • Spring MVC 400 错误请求 Ajax

    我一直在 Ajax 请求上收到 400 Bad Request 我不知道这会出什么问题 我在用着