【问题标题】:How to forward form data to another host in Spring MVC Controller?如何将表单数据转发到 Spring MVC Controller 中的另一个主机?
【发布时间】:2021-05-01 06:07:38
【问题描述】:

我有一个Controller

@Controller
public class ImageController {
    @GetMapping("/upload")
    public String uploadImageGet(Model model) {
        return "uploadForm";
    }
    @PostMapping("/upload")
    public String uploadImagePost(@ModelAttribute Image image, Model model) throws IOException {
        // what should I do here?
        return "result";
    }
}

一个 HTML 表单:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <form action="#"  th:action="@{/upload}" th:object="${image}" method="post" enctype="multipart/form-data">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" value=""><br>
        <label for="description">Description:</label><br>
        <input type="text" id="description" name="description" value=""><br>
        <label for="author">Author:</label><br>
        <input type="text" id="author" name="author" value=""><br>
        <label for="image">Image:</label><br>
        <input type="file" id="image" name="image"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

还有一个用于存储表单数据的类:

public class Image {
    private String name;
    private String author;
    private String description;
    private MultipartFile image;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public MultipartFile getImage() {
        return image;
    }

    public void setImage(MultipartFile image) {
        this.image = image;
    }
}

我想将表单数据发送到另一个主机(Spring API),但也显示“上传成功”响应页面。因此,我想在控制器中处理所有这些,但不知道如何做到这一点。我能够找到一些关于手动创建请求的资源,但这似乎必须有一些更简单的方法来做到这一点。如果我接近它是错误的,请告诉我。

【问题讨论】:

    标签: java html spring spring-boot spring-mvc


    【解决方案1】:

    这几乎取决于您的意思:

    我想将表单数据发送到另一个主机(Spring API)

    一种方法是将数据与 REST 异步发送到另一个 Spring 应用程序或使用 springs rest 模板的任何其他应用程序:https://www.baeldung.com/rest-template

    并向用户展示一个成功的 html 站点。

    但是,如果您使用异步操作,您应该记住,REST 调用可能会失败,但您会向用户显示一个成功的页面..

    我的建议是在您的 Spring Boot 应用程序中创建一个额外的 REST Endpoint,并通过 javascript 将来自站点的数据通过 fetch 或 ajax 调用发送到它,从那里可以将其发送到其他 Spring 应用程序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2016-01-31
      • 1970-01-01
      • 2020-01-23
      • 2017-04-26
      相关资源
      最近更新 更多