java 在@POST 之后将响应从 REST 发送到 JSP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33712809/
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-02 22:02:07  来源:igfitidea点击:

Send response from REST to JSP after @POST

javarestjsp

提问by ZZZ

I have a JSP page (client-side)

我有一个 JSP 页面(客户端)

<form action="http://localhost:8080/REST-WS/rest/token" method="POST">
<label for="email">Email</label>
<input name="email" />
<br/>
<label for="password">Password</label>
<input name="password" />
<br/>
<input type="submit" value="Submit" />
</form>

It points to a function in REST Web Service (server-side)

它指向 REST Web 服务(服务器端)中的一个函数

@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Code verify(@FormParam("email") String email,
@FormParam("password") String password,
@Context HttpServletResponse servletResponse) throws IOException {
    Code code = generateRandomCode(email,password);
    return token;
}

The problem is I want to give response to the client side containing the random-generated code from the server side.

问题是我想对包含来自服务器端的随机生成的代码的客户端做出响应。

First, it will be redirected to another JSP page and then the client side can receive the random-generated code from server.

首先,它将被重定向到另一个 JSP 页面,然后客户端可以从服务器接收随机生成的代码。

How do I do it?

我该怎么做?

回答by Paul Samsotha

The problem is that you can't send arbitrary Java objects in a redirect. You canhowever add the data into query parameters. For example

问题是您不能在重定向中发送任意 Java 对象。但是,您可以将数据添加到查询参数中。例如

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(@FormParam("name") String name,
                     @FormParam("email") String email) {

    String message = "Hello " + name + ". Your email is " + email;
    URI uri = UriBuilder.fromPath("/index.jsp")
            .queryParam("message", message)
            .build();
    return Response.seeOther(uri).build();
}

Here, you are building a URI from the location of the jsp page, and adding a query parameter to the end of the URI. So the redirect will go to

在这里,您将从 jsp 页面的位置构建一个 URI,并将查询参数添加到 URI 的末尾。所以重定向将转到

http://localhost:8080/index.jsp?message=<the message>

From the index.jsppage you can get the parameter with request.getParameter("message"). For example

index.jsp页面中,您可以使用request.getParameter("message"). 例如

<h1><%= request.getParameter("message") %></h1>

Another option to work with JSP and Jersey is to implement MVC, which Jersey provides support for. You can check out this answer, though the examples use Maven (to get all the required jars). If you are interested and don't know how to use Maven, let me know and I'll see if I can help you get all the jars you need.

使用 JSP 和 Jersey 的另一种选择是实现 MVC,Jersey 提供支持。您可以查看此答案,尽管示例使用 Maven(以获取所有必需的 jar)。如果您有兴趣但不知道如何使用 Maven,请告诉我,我会看看我是否可以帮助您获得所需的所有 jar。



UPDATE

更新

Ajax Example.

阿贾克斯示例。

Easiest Javascript library to get started with (if you have no experience) is jQuery. I won't really give much explanation about the code, that's kinda out of scope. I would go through some tutorials (W3Schools has some good getting started guides), and there are answers all over SO that can answer your questions.

最容易上手的 Javascript 库(如果您没有经验)是jQuery。我不会对代码给出太多解释,这有点超出范围。我会阅读一些教程(W3Schools 有一些很好的入门指南),并且到处都有可以回答您问题的答案。

Here's a complete working html page. Just change var url = "/api/submit";to whatever endpoint you are sending the request to.

这是一个完整的工作 html 页面。只需更改var url = "/api/submit";到您将请求发送到的任何端点即可。

<!DOCTYPE html>
<html>
    <head>
        <title>Ajax Example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
        <script>
            $(document).ready(function(){
                var url = "/api/submit";

                $("#submitBtn").click(function(e) {
                    e.preventDefault();

                    var formData = $("#nameForm").serialize();
                    $.ajax({
                        url: url,
                        data: formData,
                        dataType: "json",
                        type: "POST",
                        success: function(data) {
                            var message = data.message;
                            var date = data.date;

                            var h1 = $("<h1>").text(message);
                            var h3 = $("<h3>").text(date);

                            $("#content").empty()
                                    .append(h1).append(h3);
                        },
                        error: function(jqxhr, status, errorMsg) {
                            alert(status + ": " + errorMsg);
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <div id="content">
            <form id="nameForm">
                First Name: <input type="text" name="fname"/><br/>
                Last Name : <input type="text" name="lname"/><br/>
                <button id="submitBtn">Submit</button>
            </form>
        </div>
    </body>
</html>

Here is the test resource class

这是测试资源类

@Path("submit")
public class FormResource {

    public static class Model {
        public String message;
        public String date;
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Model post(@FormParam("fname") String fname,
                      @FormParam("lname") String lname) {

        String message = "Hello " + fname + " " + lname;
        Model model = new Model();
        model.message = message;
        model.date = new Date().toString();
        return model;
    }
}

You will need to make sure you have a JSON provider to handle the JSON Pojo serialization or it won't work (the Modelwon't be able to serizalize to JSON).

您需要确保您有一个 JSON 提供程序来处理 JSON Pojo 序列化,否则它将无法工作(Model将无法序列化为JSON)。