【问题标题】:Spring Failed to read HTTP message when editing entitySpring在编辑实体时无法读取HTTP消息
【发布时间】:2018-10-15 23:29:08
【问题描述】:

所以我在我的应用程序上使用 Spring mvc 和 Angularjs,由于某种原因,当我尝试更新实体 (Referencias.java) 时,我不断收到错误消息,这让我发疯,我无法弄清楚我在做什么错误的。请帮我 这是我的 angularjs 函数将对象发送到服务器:

$scope.saveReferencia = function () {
        $http.post("../index/editReferencia", $scope.referenciaEdit).then(function (r) {
        window.localStorage.setItem("referencia", JSON.stringify($scope.referenciaEdit));
        $scope.referencia = JSON.parse(window.localStorage.getItem("referencia"));
        $window.alert(r.data.mensaje);
    });
    $("#modalNuevaReferencia").modal("toggle");
};

这是我保存已编辑实体的后端 API:

    @Secured(value = "Colaborador, Editor")
    @ResponseBody
    @RequestMapping(value = "/index/editReferencia")
    public ModelAndView editReferencia(@RequestBody Referencias r, ModelMap map) {
        Referencias r1 = referenciasRepo.findOne(r.getIdReferencia());
        r1.setIdUsuario(r.getIdUsuario());
        // setting other attibrutes of the entity, didnt put them here for simplicity
        r1.setVolumen(r.getVolumen());
        try {
            referenciasRepo.saveAndFlush(r1);
            map.put("mensaje", "Referencia editada correctamente");
            map.put("data", r1);
        } catch (Exception e) {
            map.put("mensaje", "Error al actualizar la referencia");
            map.put("error", e);
        }
        return new ModelAndView(new MappingJackson2JsonView(), map);
    }

控制台出现的错误是这样的:

ADVERTENCIA [http-nio-8080-exec-26] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotReadable Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `org.springframework.security.core.GrantedAuthority` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.security.core.GrantedAuthority` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (PushbackInputStream); line: 1, column: 681] (through reference chain: models.Referencias["idUsuario"]->models.Usuarios["authorities"]->java.util.ArrayList[1])

我已经检查了一千次,发送的对象是正确的,并且包含所有必需的属性,但错误一直出现,请帮助

models.Referencias

@Entity
@Table(name = "referencias")
@NamedQueries({
    @NamedQuery(name = "Referencias.findAll", query = "SELECT r FROM Referencias r")})
public class Referencias implements Serializable {

    @JoinColumn(name = "id_usuario", referencedColumnName = "id_usuario")
    @ManyToOne
    private Usuarios idUsuario;
    @Column(name = "url")
    private String url;
    @ManyToMany
    @JoinTable(name = "categorias_por_referencias", joinColumns = {
        @JoinColumn(name = "id_referencia", referencedColumnName = "id_referencia")}, inverseJoinColumns = {
        @JoinColumn(name = "id_categoria", referencedColumnName = "id_categoria")})
    private List<Categoria> categoriaList;
    @ManyToMany
    @JoinTable(name = "autores_por_referencia", joinColumns = {
        @JoinColumn(name = "id_referencia", referencedColumnName = "id_referencia")}, inverseJoinColumns = {
        @JoinColumn(name = "id_autor", referencedColumnName = "id_autor")})
    private List<Autores> autoresList;

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_referencia")
    private Integer idReferencia;
    @Column(name = "nota")
    private String nota;
    @Column(name = "title")
    private String title;
    @Column(name = "informe_num")
    private String informeNum;
    @Column(name = "informe_tipo")
    private String informeTipo;
    @Column(name = "informe_serie")
    private String informeSerie;
    @Column(name = "informe_institution")
    private String informeInstitution;
    @Column(name = "arc_publication")
    private String arcPublication;
    @Column(name = "volumen")
    private String volumen;
    @Column(name = "num_vol")
    private String numVol;
    @Column(name = "edition")
    private String edition;
    @Column(name = "lugar")
    private String lugar;
    @Column(name = "editorial")
    private String editorial;
    @Column(name = "seccl_title")
    private String secclTitle;
    @Column(name = "tesis_universidad")
    private String tesisUniversidad;
    @Column(name = "pages")
    private String pages;
    @Column(name = "fecha")
    private String fecha;
    @Column(name = "fecha_ad")
    private String fechaAd;
    @Column(name = "fecha_mod")
    private String fechaMod;
    @JoinColumn(name = "id_fuente", referencedColumnName = "id_fuente")
    @ManyToOne(optional = false)
    private FuenteInf idFuente;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idReferencia")
    @JsonIgnore
    private List<MetadatosAlimentosG> metadatosAlimentosGList;

    // Standar constructors, getters and setters

Models.Usuarios

public class Usuarios implements Serializable, UserDetails {

    //Other attributes
    @JoinColumn(name = "id_roles", referencedColumnName = "id_roles")
    @ManyToOne(optional = false)
    private Roles idRol;

    //Constructors and other attributes´s setters and getters 

    public Roles getIdRol() {
        return idRol;
    }

    public void setIdRol(Roles idRol) {
        this.idRol = idRol;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //Maybe this is not the right implementations?
        //I think is worth mentioning every user has ONLY one role/authority on my model
        List<Roles> authority = new ArrayList<>();
        authority.add(idRol);
        return authority;
    }

}

【问题讨论】:

  • 可以发一下模特Referencias
  • 检查一下,我刚刚添加了模型“Referencias”
  • 你的问题好像是 Usuarios["authorities"],Usuario 和 Authorities 长什么样子??
  • @WilderValera 检查更新,注意 Usuarios 类中的 cmets。我也认为问题存在,但我不知道如何解决它

标签: angularjs hibernate spring-mvc


【解决方案1】:

Spring 正在尝试将您的 getAuthorities() 方法序列化为 JSON 对象。

这应该可行

@Override
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多