Spring's MVC framework encountered a 400 Bad Request error when processing an

Encountering a recurring issue with receiving a 400 Bad Request error during Ajax requests. It's puzzling as to what could be causing this problem. The technologies being used include:

<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 setup:

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

Ajax call implementation:

$(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'>Book Added: ";
                respContent += book.title;
                respContent += "</span>";

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

Details of the HTTP request:

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

The received response showing a 400 Bad Request:

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

Seeking solutions for resolving this issue. A tutorial was referenced as a starting point. Various threads have been explored but the problem still persists.

Edit: Book entity class definition:

   \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

    }

Additional Edit:

<%@ 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>Author: </label></td>
                        <td><sf:input path="author" id="author" /></td>
                        <td><sf:errors path="author" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Title: </label></td>
                        <td><sf:input path="title" id="title" /></td>
                        <td><sf:errors path="title" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Description: </label></td>
                        <td><sf:textarea path="description" id="description" /></td>
                        <td><sf:errors path="description" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Number of Pages: </label></td>
                        <td><sf:input path="pages" id="pages" /></td>
                        <td><sf:errors path="pages" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Publication Year: </label></td>
                        <td><sf:input path="publicationYear" id="publicationYear" /></td>
                        <td><sf:errors path="publicationYear" cssClas="error" /></td>
                    </tr>
                    <tr>
                        <td><label>Publisher: </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="Add" class="btn btn-primary" /></td>
                    </tr>
                </table>
            </sf:form>
        </div>

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

Answer №1

Success! I managed to resolve my issue. Here's the solution that worked for me: First, I updated the dependency to 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>

Next, I annotated my Book class with @JsonProperty and @JsonIgnore. Check out the revised Book class below:

 @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;
    }
     // Add getters and setters here

}

Answer №2

Exclude the parameter "'contentType: 'application/json'," when making the ajax request

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does Safari browser keep showing NAN instead of a value?

In my quest to calculate the difference between two times in Safari browser, I encountered an issue. The code works perfectly fine in Chrome, but in Safari, it returns NAN. When I run the application for the first time, I save today's date. On subsequ ...

The loading icon in JavaScript failed to function when JavaScript was disabled in the browser

On my blogger website, I tried using JavaScript to display a loading icon until the page completely loads. However, this method did not work when JavaScript was disabled on the browser. Only CSS seems to provide a solution. document.onreadystatechange = ...

Multiple Ajax Requests at the Same Time?

I am looking to optimize the execution of a specific PHP script on my server by making multiple calls concurrently. Each call takes approximately 0.5 seconds and is independent of one another. Currently, my implementation looks like this: $(document).read ...

Reading JSON in Spring Boot can sometimes be challenging, especially when faced with errors like "Cannot deserialize value of type `X` from Array value." This error typically occurs when trying to parse an array value

I am facing an issue with sending data from my Angular application to SpringBoot. The problem arises when the server does not receive the correct object that is being sent. Upon checking the console.log output for what is being sent to the server, everyth ...

Utilizing Jquery cycle to overlay a div on top of a scrolling image

Hey there! I'm currently using the jquery.cycle.all.js plugin for my website. I've encountered an issue where I want to position a menu div on top of an image slider. The menu is in the correct location, but unfortunately, it's hidden benea ...

Guidelines for retrieving specific json information using PHP

Hello there, I am currently retrieving data directly from an API endpoint. While I was successful in obtaining the id, I am facing difficulty in accessing the "type":"participant" part, specifically the skillTier. Even though I have written the following ...

Show loading message on keypress using jQuery

I need assistance with a unique jQuery script for the desired functionality: While inputting text into the text field, I would like the adjacent 'Load' text to be displayed. If typing stops, the 'Load' text should change to 'Del& ...

What is the best way to access and retrieve all the user search data available on Twitter through Laravel's API

Currently, I am working with the Twitter API (https://api.twitter.com/1.1/users/search.json). Whenever I make a GET request to retrieve user records, I only receive the first page of results containing 20 records in JSON format. My goal is to fetch all rec ...

Passing numerous PHP echo values to multiple text fields through jQuery AJAX

Check out my PHP file where I will be returning two echoes using jQuery Ajax <?php $data=$_POST['data1']; $data2="h"; if($data2==$data) { echo "john"; echo "usa"; } else { echo "Error"; } ?> This is how I call it with Ajax and populate ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

What is the recommended way to retrieve a "NA" value when the radio button is not chosen or unavailable?

I want to assign the value "NA" when no radio button option is selected. Currently, I am using the following code snippet: $("input[name='question']:checked").siblings('label').text(). However, this code returns a blank value if any rad ...

Best methods for sorting through a JSON array using Python

Here is the JSON array I'm currently working with. I need to extract all objects where type=1. Original data: [ { "type": 1, "name" : "name 1", }, { "type": 2 "name" : "name 2 ...

How can I integrate Solr with jQuery AJAX?

Can jQuery Ajax be utilized to send GET parameters to Solr and dynamically update the content of the page without requiring a full page reload by the user? ...

Error encountered when attempting to upload PHP file using an AJAX request

This is my HTML form validated by PHP with AJAX request. However, after submission, I encounter the following error: Notice: Undefined index: img in D:\Software Installed\xampp\htdocs\wix\users\insert_galary.php on line 12 ...

Issue encountered while retrieving a JSON response from the http request

Attempting to retrieve the response from an http request through the Hunter API. The URL resembles the following: https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname The response see ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

Rendering Nested JSON Data from Node.js to EJS Template

I find myself lost in a sea of browser tabs, with 1000 open and still unable to locate the information I need. server.js When it comes to fetching data from my neo4j database in the server, this is what I have running: app.get('/ios', async (r ...

Is there a way to download a file using an ajax request?

We are faced with a particular scenario in our application where: Client sends a request Server processes the request and generates a file Server sends the file back as a response Client's browser prompts a dialog for downloading the file Our appli ...

Can someone please provide me with the correct syntax for a jQuery AJAX PUT request that is JSON encoded?

Here is the ajax PUT request that I have written: jQuery.ajax({ url: url_lab_data+"backend/read/{\"f_anid\":"+anid+"}", type: "PUT", data: JSON.stringify({"read": 1}), ...

Redirecting to a new page in JavaScript as the clock nears the top of the hour after 5 minutes

I am looking to automatically redirect a user to another page when it is 5 minutes until the start of the next hour. In military time (24-hour clock), this means I want the redirect to occur at times like... 11:55 12:55 13:55 14:55 15:55 etc So far, I ...