java Springboot 如何在 POST 后返回响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48179716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:00:00  来源:igfitidea点击:

Springboot How to Return a response after a POST

javarestspring-bootresponse

提问by kaddie

I would like to create a new customer and return a customer number once the customer is created. The customer number has to be an auto incremented unique number from 50000.

我想创建一个新客户并在创建客户后返回一个客户编号。客户编号必须是从 50000 开始自动递增的唯一编号。

Thus far i have managed to created a customer but i am not sure how i should go about generating the customer number, save it to the database and show it to the user as a success message when a POST is triggered.

到目前为止,我已经成功创建了一个客户,但我不确定我应该如何生成客户编号,将其保存到数据库中,并在触发 POST 时将其作为成功消息显示给用户。

Below json is the desired response;

json 下面是所需的响应;

{
    "customerNumber": "50002",
    "statusMessage": "Customer Created Successfully",
} 

And the following snippet from controller and service;

以及来自控制器和服务的以下片段;

UserService.java

用户服务.java

public void createUser(User user) {
    if (user == null || user.getId() == null) {
        throw new ResourceNotFoundException("Empty", "Missing Data Exception");
    } else {
        userRepository.save(user);
    }
}

RegistrationController.java

注册控制器.java

@RequestMapping(method = RequestMethod.POST, value = "/users")
public void createUser(@RequestBody User user) {
    userService.createUser(user);
}

回答by bur?quete

Annotate the class containing createUserwith @RestController, or add @ResponseBodyon createUsermethod directly, and change its return type to Response;

对包含createUserwith的类进行注解@RestController,或者直接添加@ResponseBodyoncreateUser方法,并将其返回类型更改为Response;

@RestController
class Controller {

    @RequestMapping(method = RequestMethod.POST, value = "/users")
    public Response createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
}

Assuming your createUsermethod in UserServicewill return a Response;

假设您的createUser方法UserService将返回一个Response;

public Response createUser(User user) {
    if (user == null || user.getId() == null) {
        throw new ResourceNotFoundException("Empty", "Missing Data Exception");
    } else {
        User user = userRepository.save(user);
        return new Response(user.getId);
    }
}

Since fooRepository.save()always returns the successfully saved entity as long as it is the native savemethod from CrudRepository.

由于fooRepository.save()始终只要是本地返回成功保存实体save的方法CrudRepository

The idfield will be present inside the resulting Userentity from save, to return the type of response you want, you'd need to create such a class, and transfer the aforementioned id;

id字段将出现在结果User实体 from 中save,要返回您想要的响应类型,您需要创建这样一个类,并传输上述内容id

class Response {

    private String customerNumber;
    private String statusMessage;

    public Response(String id) {
        this.customerNumber = id;
        this.statusMessage = "Customer Created Successfully";
    }

    // getters, setters, etc
}

回答by acdcjunior

For your controller to be able to return the id, the service layer should be able to provide that information.

为了让您的控制器能够返回 id,服务层应该能够提供该信息。

In other words, a service or the repository should be able to inform you the id of the last added user. After getting that information, you can use it in the controller.

换句话说,服务或存储库应该能够通知您最后添加的用户的 ID。获得该信息后,您可以在控制器中使用它。

For example, some repository implementations set the id of the entity with the generated id after the saving (and commit of the transaction). If that was your case, you could do:

例如,一些存储库实现在保存(和提交事务)后使用生成的 id 设置实体的 id。如果这是你的情况,你可以这样做:

@RequestMapping(method = RequestMethod.POST, value = "/users")
@ResponseBody
public long createUser(@RequestBody User user){
     userService.createUser(user);
     return user.getId();
}

Notice the addition of the returnclause, the returning type and the @ResponseBodyannotation.

请注意添加了return子句、返回类型和@ResponseBody注释。