将对象从 Angular8 发送到 Spring Boot

Sending an object from Angular8 to Spring Boot

我是 Web 开发的新手,我承认按照一些在线指南,我对一些基本概念仍然有些困惑。 我有一个工作正常的 Angular8 表单:我插入数据并单击 "Submit".

onSubmit() {
    console.log(this.model);
    this.submitted = true;
  }

并在控制台打印表格的数据(我按照this official guide参考)。

这是我的search-message.tsmodel的class)的内容:

export class SearchMessage {

  constructor(
    public id: number,
    public inputText: string,
    public targetSite: string,
    public searchLimit: number,
    public details: boolean
  ) { }
}

现在我正在尝试编写一个 Spring Boot 应用程序,它将接收 model 对象,我将简单地打印输出相同的数据.此过程中不应涉及数据库(这就是我感到困惑的原因:我在网上找到的所有指南都是关于将服务器上的数据库连接到 Angular 中的视图)。我应该怎么做?

在 Spring 引导中,您必须定义一个控制器 class,它会公开一个您将从 Angular 应用程序调用的端点。

@RestController
@RequestMapping("/path")
public CustomController {
    @PostMapping("message")
    public ResponseEntity<?> addModel(@RequestBody SearchMessage message) {

        // do what you need with the element (ex. write to a db, print data..)
        System.out.println("Data received: " + message.toString());

        return ResponseEntity.ok().build();

    }
}

SearchMessage 应该是这样的:

class SearchMessage {
    private int id; 
    private String inputText;
    private String targetSite;
    private int searchLimit;
    private boolean details;

    // getters and setters
}

而且,假设后端应用程序是 运行 在端口 8081 上,您可以像这样对端点执行 post:

http://localhost:8081/your-app-context-path/path/message

其中正文必须与您在方法参数 message 中定义的 SearchMessage class 兼容。
请注意,您可以定义应用程序的上下文路径,在 application.properties 文件中添加此 属性:

server.servlet.context-path=/myCoolApp

您可以在此 Spring example. See also this more complete article 中找到完整的工作示例。
如果您需要更多详细信息或解释,请告诉我。