如何使用Thymeleaf模板引擎在Java Spark中获取表单数据?

时间:2017-02-18 14:24:01

标签: thymeleaf spark-java

我已经构建了一个简单的应用程序,现在我正尝试将其附加到Web服务器。我尝试使用一个HTML表单(使用Thymeleaf),用户以文本形式输入其位置,然后我的服务器将使用该字符串生成结果。所以要开始,我试图制作一个简单的火花应用程序,使主页上有一个"输入你的位置"表单,然后获取用户输入并使用它执行某些操作。我可以得到" entryMessage"显示,正如教程所示,但如何获取用户数据证明是困难的。

然而,关于如何使用这两个框架完成这方面的文档很少。我对代码应该是什么样子的尝试如下。请注意,中间帖只是我试图找到获取表单数据的方法 - 没有证明是成功的

    ThymeleafTemplateEngine engine = new ThymeleafTemplateEngine();
    HashMap<String, String> userLocationMap = new HashMap<>();

    get("/home", (request, response) -> {
        userLocationMap.put("entryMessage", "Please enter your location");
        return new ModelAndView(userLocationMap, "home");
    }, engine);


   post("/home", (request, response) -> {
        System.out.println(request.toString());
        //System.out.println(request.body());
        //System.out.println(userResponse.location);
        //response.redirect("/locationAccepted");
        return userLocationMap.get("userLocation");
    });

    get("/locationAccepted", (request, response) -> {
        String location = request.queryParams("userLocation");
        return new ModelAndView(userLocationMap, "locationAccepted");
    }, engine);

使用以下百里叶模板

home.html的

&#13;
&#13;
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p> <span th:text="${entryMessage}"> default message </span> </p>
<form action="/locationAccepted" method="post">
    <input type="text" th:field="userLocation"/>
    <div class="button">
        <button type="submit">Send your message</button>
    </div>
</form>
</body>
</html>
&#13;
&#13;
&#13;

和locationAccepted.html

&#13;
&#13;
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p> <span th:text="${userLocation}"> default message </span> </p>

</form>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的代码中有两个错误,都是HTML格式:

  1. 在您的Java代码中,您将路由"/locationAccepted"定义为GET,但您的表单method属性为POST =&gt;将表单更改为GET

  2. 如果您想获取表单的input数据,则应该name的值为userLocationth:field未被翻译为name(它被翻译为field属性,我不知道这意味着什么。)

  3. 所以你的形式(在Thymeleaf之后)应该是这样的:

    <form action="/locationAccepted" method="GET">
        <input type="text" name="userLocation"/>
        <div class="button">
            <button type="submit">Send your message</button>
        </div>
    </form>
    

    然后request.queryParams("userLocation")将按您的意愿运作。