原创

HttpMediaTypeNotSupportedException:不支持 Content-Type 'application/json;charset=UTF-8']

温馨提示:
本文最后更新于 2024年04月12日,已超过 37 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

I'm in the process of learning spring boot and I'm attempting to add spring security to my application. However, when I try to post a new Customer entity, I receive a "HttpMediaTypeNotSupportedException" when I send a post request from Postman that specifies the payload I send does not support 'application/json'.

Customer and User Entity :

@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Entity
@DiscriminatorValue(value = "Customer")
public class Customer extends User {

    private String phone;

    @Embedded
    @Valid
    private Address address;

    @OneToMany(mappedBy = "customer")
    @JsonManagedReference
    private List<Shipment> shipmentList;

    @OneToOne(mappedBy = "customer")
    @JsonManagedReference
    private Cart cart;


}
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "user_type")
@EntityListeners(AuditingEntityListener.class)
public class User implements UserDetails, Principal {

    @Id
    @GeneratedValue
    private Integer id;

    private String firstname;
    private String lastname;
    @NotEmpty(message = "{customer.email.not.empty}")
    @Email(message = "{customer.email.invalid}")
    @Column(unique = true, updatable = false)
    private String email;
    private String password;
    private boolean accountLocked;
    private boolean enabled;


    @Enumerated(EnumType.STRING)
    private Roles role;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    private LocalDateTime createdDate;
    @LastModifiedDate
    @Column(insertable = false, updatable = true)
    private LocalDateTime lastModifiedDate;

    @Override
    public String getName() {
        return email; //email is the unique identifier of the User
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of(new SimpleGrantedAuthority(role.name()));
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !accountLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    private String fullName(){
        return firstname + lastname;
    }
}

CustomerDTO :

public record CustomerDTO(
    @NotEmpty(message = "{customer.name.not.empty}")
    String firstname,
    @NotEmpty(message = "{customer.name.not.empty}")
    String lastname,
    @NotEmpty(message = "{customer.email.not.empty}")
    @Email
    String email,
    String phone,
    Address address,
    @Valid
    Cart cart,
    @Valid
    List<Shipment> shipments
){}

createCustomer() in CustomerService:

public CustomerDTO createCustomer(CustomerDTO customerDTO) throws CustomerAlreadyExistsException, CustomerCreateNotValidException {
        //first validate the DTO being sent in
        validator.validate(customerDTO, "Invalid fields of new customer") ;
        //check if this customer already exists
        if(repository.findByEmail(customerDTO.email()) == null){
            Customer customer = mapper.customerDTOToCustomer(customerDTO);
            repository.save(customer);
        } else {
            throw new CustomerAlreadyExistsException(environment.getProperty("service.customer.already.exists"));
        }
        return customerDTO;
    }

createCustomer() in CustomerController:

 @PostMapping(value = "customers")
    public ResponseEntity<?> createCustomer(@RequestBody CustomerDTO customerDTO) throws CustomerAlreadyExistsException, CustomerCreateNotValidException {
        CustomerDTO createdCustomer = customerService.createCustomer(customerDTO);
        return new ResponseEntity<>(createdCustomer, HttpStatus.CREATED);
    }

Postman payload and response

Postman header

I understand that 'application/json" is the default content-type that Spring Boot uses through Jackson so I am confused about this error. I have also specified inside the headers of my post request in Postman that the Content-type is application.json but I still receive the error.

I have also checked if my CustomerDTO could be a mismatch with the payload I am sending to my controller, but that does not seem to be the case either since every field seems to match.

Prior to adding spring security to my application, I was successfully able to post new Customers. But after I changed Customer Entity to be able to inherit from a custom User Entity which implements the UserDetails interface from springframework.security.core, I am having issues posting a new customer. Is Inheritance the cause of the issue?

Also, I am using mapstruct to automatically generate the mappings from entity to DTO, could this also be the source of the issue?

正文到此结束
热门推荐
本文目录