简体   繁体   中英

"Unsupported Media Type" in spring boot - Windows

I have a User class like this :

@Data
@Entity
public class User {
    @Id
    @GeneratedValue
    Long userID;

    String eMail;

    String passwordHash;

    //ArrayList<ClassRoom>adminOf=new ArrayList<>();

    User() {}

    public User(String eMail, String passwordHash) {
        this.eMail = eMail;
        this.passwordHash = passwordHash;
    }
}

And in a LoadDatabase class I have :

@Bean
CommandLineRunner initDatabase(UserRepository userRepository) {
    return args -> {
        log.info("Preloading " + userRepository.save(new User("admin@admin.com", "asdasd")));
        log.info("Preloading " + userRepository.save(new User("admin@admin.com", "12345")));
    };
}

Which give me this :

弹簧靴预加载

Now in when I give curl -v localhost:8080/user this command it gives me this :

spring-boot curl get

Which is pretty correct, although it gives me email instead of eMail .

But when I give

curl -X PUT localhost:8080/user/3 -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"admin1@admin.com"}'

it says :

弹簧靴卷曲柱

Which is pretty horrific. I'm following this tutorial.

And here is my UserController class:

package com.mua.cse616.Controller;


import com.mua.cse616.Model.User;
import com.mua.cse616.Model.UserNotFoundException;
import org.springframework.web.bind.annotation .*;

import java.util.List;

@RestController
class UserController {

    private final UserRepository repository;

    UserController(UserRepository repository) {
        this.repository = repository;
    }

    // Aggregate root

    @GetMapping("/user")
    List<User> all() {
        return repository.findAll();
    }

    @PostMapping("/user")
    User newUser(@RequestBody User newUser) {
        return repository.save(newUser);
    }

    // Single item

    @GetMapping("/user/{id}")
    User one(@PathVariable Long id) {

        return repository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));
    }

    @PutMapping("/user/{id}")
    User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

        return repository.findById(id)
                .map(employee -> {
                    employee.setEMail(newUser.getEMail());
                    employee.setPasswordHash(newUser.getPasswordHash());
                    return repository.save(employee);
                })
                .orElseGet(() -> {
                    newUser.setUserID(id);
                    return repository.save(newUser);
                });
    }

    @DeleteMapping("/user/{id}")
    void deleteUser(@PathVariable Long id) {
        repository.deleteById(id);
    }
}

Put method after updating :

@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

    return repository.findById(id)
            .map(employee -> {
                employee.setEMail(newUser.getEMail());
                employee.setPasswordHash(newUser.getPasswordHash());
                return repository.save(employee);
            })
            .orElseGet(() -> {
                newUser.setUserID(id);
                return repository.save(newUser);
            });
}

Now there arise two questions .

  • Why email instead of eMail , what to do to get eMail instead of email
  • How to POST correctly, what I'm doing wrong?

" Why email instead of eMail " - That is just the default behavior of Jackson.

" what to do to get eMail instead of email " - You can control Jackson's behavior through annotations on the POJO. The relevant here is @JsonProperty . See this question for details.

" How to POST correctly, what I'm doing wrong? " - You mean PUT instead of POST , don't you? Define the content type consumed by the method:

@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {
    ...
}

Also, as was pointed out by @rimonmostafiz, you need to redefine your curl call, escaping the quotation:

curl -X PUT -H "Content-Type: application/json" -d "{ \"email\": \"asd\", \"passwordHash\": \"sad\" }"

As an aside: Please limit yourself to one question per post in the future.

Add missing consumes attribute on @PutMapping annotation,

@PutMapping(path= "/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

although it gives me email instead of eMail

It all depends on your getter/setter of property eMail in your User entity. I think your getter must be getEmail() and hence conventionally you get in response email as JSON property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM