【发布时间】:2019-12-05 21:09:11
【问题描述】:
我有一个像这样的User 课程:
@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;
}
}
在LoadDatabase 课程中我有:
@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")));
};
}
给我这个:
现在当我给curl -v localhost:8080/user这个命令时,它给了我这个:
这是非常正确的,虽然它给了我email 而不是eMail。
但是当我给的时候
curl -X PUT localhost:8080/user/3 -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"admin1@admin.com"}'
上面写着:
这太可怕了。我正在关注this 教程。
这是我的UserController 课程:
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方法:
@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);
});
}
现在有两个问题。
- 为什么是
email而不是eMail,怎么办才能得到eMail而不是email - 如何正确
POST,我做错了什么?
【问题讨论】:
-
"为什么用
email而不是eMail,怎么办才能得到eMail而不是电子邮件" - 这就是杰克逊的行为方式。有注释,例如@JsonProperty,控制其行为。有关详细信息,请参阅this question。 --- "如何正确设置POST,我做错了什么?" - 你试过设置@PutMapping(..., consumes = MediaType.APPLICATION_JSON_VALUE, ...)吗? --- 备注:以后请限制自己在每个帖子中回答一个问题。 -
您使用的是哪个操作系统?
-
从下次开始,我会尽量记住这一点......我在 Windows 10 上......
标签: java spring spring-boot curl