【问题标题】:Spring boot application POST request not works and not update the databaseSpring Boot 应用程序 POST 请求不起作用并且不更新数据库
【发布时间】:2020-02-20 11:48:08
【问题描述】:

我有 java Spring Boot 应用程序。当我通过 POSTman 发送数据 POST 请求时。 JSONObject 无法返回,POSTman 显示 {"false"}

这是我的控制器, 包 com.lagoma.demo.controller;

@RestController
@RequestMapping(value = "/user")

public class User {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<UserModel> getUsers() {
        return userService.getUsers();


    }

    @RequestMapping(method = RequestMethod.GET, value = "/get")
    public UserModel getOneUser(@RequestParam(value = "id", required = false, defaultValue = "00") int id) {
        return userService.getUser(id);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public boolean updateUser(@RequestBody UserModel userModel){
        return userService.updateUser(userModel);
    }

【问题讨论】:

  • 你到底有什么问题,用户没有保存或用户没有返回?

标签: json spring post intellij-idea postman


【解决方案1】:

Spring Controller 不能返回原始类型或其包装器。

你需要返回一些对象。

如果您在范围内没有任何对象,返回 Map 也可以。

把你的 updateUser 改成这样的

@RequestMapping(method = RequestMethod.POST, value = "/save")
public Map<String, Boolean> updateUser(@RequestBody UserModel userModel){
    return Collections.singletonMap("result", userService.updateUser(userModel));
}

或使用对象

@RequestMapping(method = RequestMethod.POST, value = "/save")
public User updateUser(@RequestBody UserModel userModel){
    // assuming userService.updateUser will return User object
    User user = userService.updateUser(userModel); 
    return user;
}

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2020-05-12
    • 2018-08-06
    • 2017-11-05
    相关资源
    最近更新 更多