在js / spring boot / hibernate项目中出错

时间:2016-10-27 20:13:39

标签: javascript spring-security spring-boot datatable datatables

我正在尝试使用JavaScript在Spring Boot上做一些项目,但我有很多错误。他们在这里:

  

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:   无法将[java.lang.String]类型的值转换为所需类型   [INT];嵌套异常是java.lang.NumberFormatException:用于输入   string:“filterByData”   引起:java.lang.NumberFormatException:对于输入字符串:   “filterByData”

我在项目中找不到这个“filterByData”,我给出了什么参数,比如int insteed of String。 我的实体:

@NamedQueries({
        @NamedQuery(name = Contact.GET, query = "SELECT cont FROM Contact cont WHERE cont.id=:id AND cont.user.id=:userId"),
        @NamedQuery(name = Contact.ALL_SORTED, query = "SELECT cont FROM Contact cont WHERE cont.user.id=:userId ORDER BY cont.firstName DESC"),
        @NamedQuery(name = Contact.DELETE, query = "DELETE FROM Contact cont WHERE cont.id=:id AND cont.user.id=:userId"),
        @NamedQuery(name = Contact.GET_FILTERED, query = "SELECT cont FROM Contact cont WHERE cont.user.id=:userId " +
                "AND cont.firstName LIKE :fName AND cont.lastName LIKE :lName " +
                "AND cont.mobilePhone LIKE :mPhone ORDER BY cont.firstName DESC"),
})
@Entity
@Table(name = "contacts")
public class Contact extends BaseEntity{

    public static final String GET = "Contact.GET";
    public static final String ALL_SORTED = "Contact.ALL_SORTED";
    public static final String DELETE = "Contact.DELETE";
    public static final String GET_FILTERED = "Contact.GET_FILTERED";
    @Column(name = "first_name", nullable = false)
    @NotEmpty
    @Length(min = 4)
    private String firstName;
    @Column(name = "last_name", nullable = false)
    @NotEmpty
    @Length(min = 4)
    private String lastName;
    @Column(name = "patronymic", nullable = false)
    @NotEmpty
    @Length(min = 4)
    private String patronymic;
    @Column(name = "mobile_phone_number", nullable = false)
    @NotEmpty
    @Pattern(regexp = "\\+380\\([1-9]{2}\\)[0-9]{7}", message = "format should be like +380(66)1234567" +
            "")
    private String mobilePhone;
    @Column(name = "home_phone_number")
    private String homePhone;
    @Column(name = "address")
    private String address;
    @Email
    @Column(name = "email", nullable = false)
    private String email;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    @JsonBackReference
    private User user;

    public Contact() {
    }

    public Contact(String firstName, String lastName, String patronymic, String mobilePhone, String homePhone, String address, String email ) {
        this(null,firstName,lastName,patronymic,mobilePhone,homePhone,address,email);
    }

    public Contact( Integer id, String firstName, String lastName, String patronymic, String mobilePhone, String homePhone, String address, String email ) {
        super(id);
        this.firstName = firstName;
        this.lastName = lastName;
        this.patronymic = patronymic;
        this.mobilePhone = mobilePhone;
        this.homePhone = homePhone;
        this.address = address;
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPatronymic() {
        return patronymic;
    }

    public void setPatronymic(String patronymic) {
        this.patronymic = patronymic;
    }

    public String getMobilePhone() {
        return mobilePhone;
    }

    public void setMobilePhone(String mobilePhone) {
        this.mobilePhone = mobilePhone;
    }

    public String getHomePhone() {
        return homePhone;
    }

    public void setHomePhone(String homePhone) {
        this.homePhone = homePhone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Contact{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", patronymic='" + patronymic + '\'' +
                ", mobilePhone='" + mobilePhone + '\'' +
                ", homePhone='" + homePhone + '\'' +
                ", address='" + address + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}


  @NamedEntityGraphs({
            @NamedEntityGraph(name = User.GRAPH_WITH_ROLES, attributeNodes = @NamedAttributeNode("roles")),
            @NamedEntityGraph(name = User.GRAPH_WITH_ROLES_AND_CONTACTS, attributeNodes =
                    {
                            @NamedAttributeNode("roles"),
                            @NamedAttributeNode("contacts")
                    })
    })
    @NamedQueries({
            @NamedQuery(name = User.DELETE, query = "DELETE FROM User u WHERE u.id=:id"),
            @NamedQuery(name = User.BY_LOGIN, query = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles WHERE u.login=:login"),
            @NamedQuery(name = User.ALL_SORTED, query = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles ORDER BY u.login"),
    })
    @Entity
    @Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = "login", name = "users_unique_login_idx")})
    public class User extends NamedEntity{

        public static final String GRAPH_WITH_ROLES = "User.WithRoles";
        public static final String GRAPH_WITH_ROLES_AND_CONTACTS = "User.WithRolesAndContacts";
        public static final String DELETE = "User.DELETE";
        public static final String BY_LOGIN = "User.BY_LOGIN";
        public static final String ALL_SORTED = "User.All_SORTED";


        @Column(name = "password", nullable = false)
        @Length(min = 5, max = 100, message = "your password should have 5 or more symbols")
        @JsonView(View.REST.class)
        @NotEmpty
        private String password;

        @Column(name = "full_name", nullable = false)
        @Length(min = 5, max = 100, message = "your fullName should have 5 or more symbols")
        private String fullName;

        @Enumerated(EnumType.STRING)
        @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
        @Column(name = "role")
        @ElementCollection(fetch = FetchType.LAZY)
        protected Set<Role> roles;

        @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "user")
        @OrderBy("firstName DESC")
        @JsonManagedReference
        protected List<Contact> contacts;

        public User() {
        }

        public User(User u) {
            this(u.getId(), u.getLogin(), u.getPassword(), u. getFullName(), u.getRoles());
        }

        public User(Integer id, String login, String password, String fullName, Role role, Role... roles) {
            this(id, login, password, fullName, EnumSet.of(role, roles));
        }

        public User(Integer id, String login, String password, String fullName, Set<Role> roles) {
            super(id, login);
            this.password = password;
            this.fullName = fullName;
            setRoles(roles);
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getFullName() {
            return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

        public Set<Role> getRoles() {
            return roles;
        }

        public void setRoles(Set<Role> roles) {
            this.roles = CollectionUtils.isEmpty(roles) ? Collections.emptySet() : EnumSet.copyOf(roles);
        }
        public List<Contact> getContacts() {


   return contacts;
    }

    @Override
    public String toString() {
        return "User{" +
                "password='" + password + '\'' +
                ", fullName='" + fullName + '\'' +
                ", roles=" + roles +
                '}';
    }
}

控制器:

@Controller
public class RootController extends AbstractUserController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String root() {
        return "redirect:/contacts";
    }

    @RequestMapping(value = "/contacts", method = RequestMethod.GET)
    public String contactList() {
        return "contacts";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @PreAuthorize("hasRole('ROLE_USER')")
    public String login(ModelMap model,
                        @RequestParam(value = "error", required = false) boolean error,
                        @RequestParam(value = "message", required = false) String message) {

        model.put("error", error);
        model.put("message", message);
        return "login";
    }
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(ModelMap model) {
        model.addAttribute("userDTO", new UserDTO());
        model.addAttribute("register", true);
        return "contacts";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String saveRegister(@Valid UserDTO userDTO, BindingResult result, SessionStatus status, ModelMap model) {
        if (!result.hasErrors()) {
            try {
                super.create(UserUtil.createNewUserFromDTO(userDTO));
                status.setComplete();
                return "redirect:login?message=app.registered";
            } catch (DataIntegrityViolationException ex) {
                result.rejectValue("Login", "---");
            }
        }
        model.addAttribute("register", true);
        return "contacts";
    }
}

@RestController
@RequestMapping(value = "/ajax/contacts")
public class ContactAjaxController extends AbstractContactController{

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Contact> getAll() {
        return super.getAll();
    }

    @RequestMapping(value = "/{id}")
    public Contact get(@PathVariable("id") int id) {
        return super.get(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable("id") int id) {
        super.delete(id);
    }

    @RequestMapping(method = RequestMethod.POST)
    public void updateOrCreate(@Valid Contact contact) {
        if (contact.isNew()) {
            super.create(contact);
        } else {
            super.update(contact, contact.getId());
        }
    }

    @RequestMapping(value = "/filter", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Contact> getFiltered(
            @RequestParam(value = "fName", required = false) String fName,
            @RequestParam(value = "lName", required = false) String lName,
            @RequestParam(value = "mPhone", required = false) String mPhone) {
        return super.getFiltered(fName, lName, mPhone);
    }
}
@RestController
@RequestMapping("/ajax/users")
public class UserAjaxController extends AbstractUserController{

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @JsonView(View.UI.class)
    public List<User> getAll() {
        return super.getAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @JsonView(View.UI.class)
    public User get(@PathVariable("id") int id) {
        return super.get(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable("id") int id) {
        super.delete(id);
    }

    @RequestMapping(method = RequestMethod.POST)
    public void createOrUpdate(@Valid UserDTO userTo) {
            if (userTo.isNew()) {
                super.create(UserUtil.createNewUserFromDTO(userTo));
            } else {
                super.update(userTo);
            }
    }
}

JavaScript文件:

var ajaxUrl = 'ajax/contacts/';
var datatableApi;

function updateTable() {
    $.ajax({
        type: "POST",
        url: ajaxUrl + 'filter',
        data: $('#filter').serialize(),
        success: updateTableByData
    });
    return false;
}

$(function () {
    datatableApi = $('#datatable').DataTable({
        "ajax": {
            "url": ajaxUrl,
            "dataSrc": ""
        },
        "paging": false,
        "info": true,
        "columns": [
            {
                "data": "firstName"
            },
            {
                "data": "lastName"
            },
            {
                "data": "patronymic"
            },
            {
                "data": "mobilePhone"
            },
            {
                "data": "homePhone"
            },
            {
                "data": "address"
            },
            {
                "data": "email"
            },
            {
                "defaultContent": "",
                "orderable": false,
                "render": renderEditBtn
            },
            {
                "defaultContent": "",
                "orderable": false,
                "render": renderDeleteBtn
            }
        ],
        "order": [
            [
                0,
                "desc"
            ]
        ],
        "initComplete": function () {
            $('#filter').submit(function () {
                updateTable();
                return false;
            });
            makeEditable();
        }
    });
});

var form;

function makeEditable() {
    form = $('#detailsForm');

    form.submit(function () {
        save();
        return false;
    });

    $(document).ajaxError(function (event, jqXHR, options, jsExc) {
        failNoty(event, jqXHR, options, jsExc);
    });

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

function add() {
    form.find(":input").val("");
    $('#id').val(null);
    $('#editRow').modal();
}

function updateRow(id) {
    $.get(ajaxUrl + id, function (data) {
        $.each(data, function (key, value) {
            form.find("input[name='" + key + "']").val(value);
        });
        $('#editRow').modal();
    });
}

function deleteRow(id) {
    $.ajax({
        url: ajaxUrl + id,
        type: 'DELETE',
        success: function () {
            updateTable();
            successNoty('Deleted');
        }
    });
}

function updateTableByData(data) {
    datatableApi.clear().rows.add(data).draw();
}

function save() {
    $.ajax({
        type: "POST",
        url: ajaxUrl,
        data: form.serialize(),
        success: function () {
            $('#editRow').modal('hide');
            updateTable();
            successNoty('Saved');
        }
    });
}

var failedNote;

function closeNoty() {
    if (failedNote) {
        failedNote.close();
        failedNote = undefined;
    }
}

function successNoty(text) {
    closeNoty();
    noty({
        text: text,
        type: 'success',
        layout: 'bottomRight',
        timeout: true
    });
}

function failNoty(event, jqXHR, options, jsExc) {
    closeNoty();
    var errorInfo = $.parseJSON(jqXHR.responseText);
    failedNote = noty({
        text: 'Failed: ' + jqXHR.statusText + '<br>' + errorInfo.cause + '<br>' + errorInfo.details.join('<br>'),
        type: 'error',
        layout: 'bottomRight'
    });
}

function renderEditBtn(data, type, row) {
    if (type == 'display') {
        return '<a class="btn btn-xs btn-primary" onclick="updateRow(' + row.id + ');">Edit</a>';
    }
    return data;
}

function renderDeleteBtn(data, type, row) {
    if (type == 'display') {
        return '<a class="btn btn-xs btn-danger" onclick="deleteRow(' + row.id + ');">Delete</a>';
    }
    return data;
}

我的基本CRUD方法在没有“过滤器”的情况下正常工作,每次都会出现这种错误。有人可以告诉我我做错了什么吗?感谢。

public abstract class AbstractUserController {

    @Autowired
    private UserService service;

    public List<User> getAll() {
        return service.getAll();
    }

    public User get(int id){
        return service.get(id);
    }

    public User create(User user) {
        user.setId(null);
        return service.save(user);
    }

    public void delete(int id){
        service.delete(id);
    }

    public void update(User user, int id) {
        user.setId(id);
        service.update(user);
    }

    public void update(UserDTO userDTO) {
        service.update(userDTO);
    }

    public User getByLogin(String login) {
        return service.getByLogin(login);
    }
}

0 个答案:

没有答案