Mozzila Firefox中出现400错误请求错误

时间:2020-12-12 15:47:11

I am trying to add a student in my database using Hibernate. I got a 400 Bad Request Error in Mozzila Firefox.

我正在尝试使用Hibernate在我的数据库中添加一个学生。我在Mozzila Firefox中遇到了400 Bad Request Error。

---------DAOImpl - here is DAO's method that insert a user in the DB---------

--------- DAOImpl - 这是DAO在DB中插入用户的方法---------

public void save(Student student) {
        LOG.debug(
                "inside save method from StudentDAOImpl with parameter student: {}",
                student);

        Session session = this.sessionFactory.openSession();

        session.save(student);
    }

  ------  ServiceImpl -here is service's method --------


     public void add(Student student) {

                LOG.debug(
                        "inside add method from StudentServiceImpl with parameter student: {}",
                        student);

                studentDAO.save(student);
            }

  ------  StudentController - this is controller's method for add a student -------


     @RequestMapping(value = RequestURL.ADD_STUDENT, method = RequestMethod.POST)
            @ResponseBody
            public void addStudent(@RequestBody AddStudentRequest addStudentRequest) {

                User user = new User(addStudentRequest.getUsername(),
                        addStudentRequest.getPassword(), Role.ROLE_STUDENT);
                userService.add(user);

                System.out.println("am salvat user-ul");
                user = userService.findByUsername(addStudentRequest.getUsername());
                int userId = user.getId();
                try {
                    int groupId = studentGroupService
                            .getIdByGroupNumber(addStudentRequest.getGroup());
                    int specializationId = specializationService
                            .getIdByName(addStudentRequest.getSpecialization());
                    Student student = new Student(userId, specializationId,
                            addStudentRequest.getName(),
                            addStudentRequest.getRegistrationNumber(), groupId,
                            addStudentRequest.getYear());
                    studentService.add(student);
                } catch (StudentGroupNumberNotFoundException e) {
                    e.printStackTrace();
                } catch (SpecializationNotFoundException e) {
                    e.printStackTrace();
                }
            }

  -------  student.jsp - jsp page for student ------

function addStudent() {

        var username = $('#modalStudentUsername').val;
        var password = $('#modalStudentPassword').val();
        var name = $('#modalStudentName').val;
        var registrationNumber = $('#modalStudentRegistrationNumber').val;
        var group = $('#modalStudentGroup').val;
        var year = $('#modalStudentYear').val;
        var specialization = $('#modalStudentSpecializationId').val;

        var data = '{ "username" : "' + username + '", "password": "'
        + password + '", "name":"' + name
        + '","registrationNumber": "' + registrationNumber + '" , "specialization": "' + specialization 
        + '","group": "' + group+'", "year": " ' + year + '" }';

        var token = $('#csrfToken').val();
        var header = $('#csrfHeader').val();

        $.ajax({
                    type : "POST",
                    url : "student/add",
                    contentType : 'application/json',
                    data : data,

                    beforeSend : function(xhr) {
                        xhr.setRequestHeader("Accept", "application/json");
                        xhr.setRequestHeader("Content-Type", "application/json");
                        xhr.setRequestHeader(header, token);
                    }, 

                    success : function(data, status, xhr) {
                        alert("Studentul a fost adaugat cu succes!");
                    },
                    error : function(xhr, status, errorThrown) {
                        alert("Student nu a fost salvat, deoarece a intervenit o eroare!");
                    },
                });
    }

<body>
    <input type="hidden" id="csrfToken" value="${_csrf.token}" />
    <input type="hidden" id="csrfHeader" value="${_csrf.headerName}" />
</body>

    If there are anyone who can help me, i will be very grateful! Thanks!

2 个解决方案

#1


Do you have any transaction management configured? The service add method (or the DAO save method) should either have a transaction configured, or you start a transaction from Hibernate Session.beginTransaction() and then manually commit it.

您是否配置了任何事务管理?服务添加方法(或DAO保存方法)应该配置一个事务,或者从Hibernate Session.beginTransaction()启动一个事务,然后手动提交它。

the error might be raised because you have an unhandled exception raised in your code (can be a NullPointerException on accessing the return from findByUsername, because the save was not committed, I cannot tell unless I see the finder's code).

可能会引发错误,因为你的代码中有一个未处理的异常(在访问findByUsername的返回时可能是NullPointerException,因为没有提交保存,除非我看到finder的代码,否则我无法判断)。

Also, it might be raised because on the server-side the de-serialization of the request body into AddStudentRequest instance was not possible (maybe different parameter names, or expected types). You have to check to see if the names of the parameters you set-up in the request, are the same as the attribute names in AddStudentRequest class, and also the expected types are compatible with that you send in the request.

此外,它可能会被引发,因为在服务器端,请求体到AddStudentRequest实例的反序列化是不可能的(可能是不同的参数名称或预期类型)。您必须检查您在请求中设置的参数的名称是否与AddStudentRequest类中的属性名称相同,并且期望的类型与您在请求中发送的类型兼容。

#2


You should use val() method to get the value of a particular form field instead of just val because the second one will throw an error as there's no such property in jQuery wrapper object.

您应该使用val()方法来获取特定表单字段的值而不仅仅是val,因为第二个将抛出错误,因为jQuery包装器对象中没有这样的属性。

Change your code like below to use val()

像下面一样更改代码以使用val()

    var username = $('#modalStudentUsername').val();
    var password = $('#modalStudentPassword').val();
    var name = $('#modalStudentName').val();
    var registrationNumber = $('#modalStudentRegistrationNumber').val();
    var group = $('#modalStudentGroup').val();
    var year = $('#modalStudentYear').val();
    var specialization = $('#modalStudentSpecializationId').val();

You can even combine the initialization of these variables like

你甚至可以将这些变量的初始化结合起来

    var username = $('#modalStudentUsername').val(),
        password = $('#modalStudentPassword').val(),
        name = $('#modalStudentName').val();

You don't have to concate all these vars as strings, you can simply create a javascript object to hold your variables, jQuery will take care of conversion while making the AJAX call.

您不必将所有这些变量作为字符串连接,您只需创建一个javascript对象来保存变量,jQuery将在进行AJAX调用时处理转换。

    var data = { 
       "username" : username ,
       "password": password ,
       "name": name,
       "registrationNumber": registrationNumber,
       "specialization": specialization ,
       "group": group,
       "year": year
    };

#1


Do you have any transaction management configured? The service add method (or the DAO save method) should either have a transaction configured, or you start a transaction from Hibernate Session.beginTransaction() and then manually commit it.

您是否配置了任何事务管理?服务添加方法(或DAO保存方法)应该配置一个事务,或者从Hibernate Session.beginTransaction()启动一个事务,然后手动提交它。

the error might be raised because you have an unhandled exception raised in your code (can be a NullPointerException on accessing the return from findByUsername, because the save was not committed, I cannot tell unless I see the finder's code).

可能会引发错误,因为你的代码中有一个未处理的异常(在访问findByUsername的返回时可能是NullPointerException,因为没有提交保存,除非我看到finder的代码,否则我无法判断)。

Also, it might be raised because on the server-side the de-serialization of the request body into AddStudentRequest instance was not possible (maybe different parameter names, or expected types). You have to check to see if the names of the parameters you set-up in the request, are the same as the attribute names in AddStudentRequest class, and also the expected types are compatible with that you send in the request.

此外,它可能会被引发,因为在服务器端,请求体到AddStudentRequest实例的反序列化是不可能的(可能是不同的参数名称或预期类型)。您必须检查您在请求中设置的参数的名称是否与AddStudentRequest类中的属性名称相同,并且期望的类型与您在请求中发送的类型兼容。

#2


You should use val() method to get the value of a particular form field instead of just val because the second one will throw an error as there's no such property in jQuery wrapper object.

您应该使用val()方法来获取特定表单字段的值而不仅仅是val,因为第二个将抛出错误,因为jQuery包装器对象中没有这样的属性。

Change your code like below to use val()

像下面一样更改代码以使用val()

    var username = $('#modalStudentUsername').val();
    var password = $('#modalStudentPassword').val();
    var name = $('#modalStudentName').val();
    var registrationNumber = $('#modalStudentRegistrationNumber').val();
    var group = $('#modalStudentGroup').val();
    var year = $('#modalStudentYear').val();
    var specialization = $('#modalStudentSpecializationId').val();

You can even combine the initialization of these variables like

你甚至可以将这些变量的初始化结合起来

    var username = $('#modalStudentUsername').val(),
        password = $('#modalStudentPassword').val(),
        name = $('#modalStudentName').val();

You don't have to concate all these vars as strings, you can simply create a javascript object to hold your variables, jQuery will take care of conversion while making the AJAX call.

您不必将所有这些变量作为字符串连接,您只需创建一个javascript对象来保存变量,jQuery将在进行AJAX调用时处理转换。

    var data = { 
       "username" : username ,
       "password": password ,
       "name": name,
       "registrationNumber": registrationNumber,
       "specialization": specialization ,
       "group": group,
       "year": year
    };