在HTML中使用Thymeleaf显示数据。

huangapple go评论30阅读模式
英文:

Display data on HTML using Thymeleaf

问题

以下是您提供的内容的翻译:

我想显示从搜索获取的与我的口味相关的数据。目前,它只是纯文本。

例如,我正在搜索“泰坦尼克号”,然后我得到了电影名称、一些链接以及来自IMDB的一些信息。

我有以下代码:

search.html

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>入门:处理表单提交</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>表单</h1>
<form action="#" th:action="@{/search}" th:object="${search}" method="post">
    <p>消息: <input type="text" th:field="*{content}" /></p>
    <p><input type="submit" value="提交" /> <input type="reset" value="重置" /></p>
</form>
</body>
</html>

result.html

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>入门:处理表单提交</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>结果</h1>
<p th:text="'内容: ' + ${main.content}"></p>
<a href="/search">提交另一条消息</a>
</body>
</html>

SearchController.java

@Controller
public class SearchController {
    @GetMapping("/search")
    public String greetingForm(Model model) {
        model.addAttribute("search", new Main());
        model.addAttribute("main", new Main().getContent());
        return "search";
    }

    @PostMapping("/search")
    public String greetingSubmit(@ModelAttribute Main main) {
        return "result";
    }
}

Main.java

private String content;
private List<Result> finalList;
private List<Result> resultList;

public void setContent(String content) throws IOException {
 //计算finalList的代码
}

public List<Result> getContent() {
    return this.finalList;
}

主要问题是我不知道从哪里开始。finalList 是一个类型为“Result”的对象列表,它具有字段,例如

private List<String> link = new ArrayList<>();
private String name;
private TitleProp titleProp;

TitleProp 具有

private String trailer;
private String rating;
private String description;
private String genre;

我想要操作每个字段以以不同的方式显示它,比如以表格的形式显示更多行等。任何链接或代码示例都将帮助我更好地理解Thymeleaf和Spring Boot。

请注意,这些只是您提供内容的翻译,不包括额外的回答或解释。如果您需要更多帮助,请告诉我。

英文:

I would like to display the data I get from a search, personalized for my taste. At this moment, It is just plain text.

For example, I am searching for "Titanic", and I get the name, a few links, and some information from IMDB.

I have the following code:

search.html

&lt;!DOCTYPE HTML&gt;
&lt;html xmlns:th=&quot;https://www.thymeleaf.org&quot;&gt;
&lt;head&gt;
    &lt;title&gt;Getting Started: Handling Form Submission&lt;/title&gt;
    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Form&lt;/h1&gt;
&lt;form action=&quot;#&quot; th:action=&quot;@{/search}&quot; th:object=&quot;${search}&quot; method=&quot;post&quot;&gt;
    &lt;p&gt;Message: &lt;input type=&quot;text&quot; th:field=&quot;*{content}&quot; /&gt;&lt;/p&gt;
    &lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt; &lt;input type=&quot;reset&quot; value=&quot;Reset&quot; /&gt;&lt;/p&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

result.html

 &lt;!DOCTYPE HTML&gt;
&lt;html xmlns:th=&quot;https://www.thymeleaf.org&quot;&gt;
&lt;head&gt;
    &lt;title&gt;Getting Started: Handling Form Submission&lt;/title&gt;
    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Result&lt;/h1&gt;
&lt;p th:text=&quot;&#39;content: &#39; + ${main.content}&quot;&gt;&lt;/p&gt;
&lt;a href=&quot;/search&quot;&gt;Submit another message&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;

SearchController.java

    @Controller
public class SearchController {
    @GetMapping(&quot;/search&quot;)
    public String greetingForm(Model model) {
        model.addAttribute(&quot;search&quot;, new Main());
        model.addAttribute(&quot;main&quot;, new Main().getContent());
        return &quot;search&quot;;
    }

    @PostMapping(&quot;/search&quot;)
    public String greetingSubmit(@ModelAttribute Main main) {
        return &quot;result&quot;;
    }
}

and Main.java

    private String content;
private List&lt;Result&gt; finalList;
private List&lt;Result&gt; resultList;

public void setContent(String content) throws IOException {
 //code to compute finalList
}

public List&lt;Result&gt; getContent() {
    return this.finalList;
}

The main problem is that I have no ideea where to being with. finalList is a list of objects of type "Result", which have fields such as

private List&lt;String&gt; link = new ArrayList&lt;&gt;();
private String name;
private TitleProp titleProp;

and TitleProp has

private String trailer;
private String rating;
private String description;
private String genre;

I would like to manipulate each field to show it on a different way, such as a table with more rows, etc.
Any link or sample of code would help me a lot to understand Thymeleaf and Spring Boot more.

答案1

得分: 1

I am coming with an answer to my question. I managed to get the result I wanted using Ajax, as SnakeDoc suggested. It was a long road, mostly because even if I had a working code, I spent a few hours searching for the Forbidden 403 error on ajax post request.

So, for the js part:

function ajaxPost() {
    // Here we prepare data for the JSON
    var formData = {
        moviename: $("#moviename").val()
    }
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "MYURL",
        data: JSON.stringify(formData),
        dataType: 'json',
        success: function (result) {
            {
                $.each(result,
                    function (i, title) {
                        // do whatever you want with what you got from the server
                    });
                console.log("Success: ", result);
            }
            console.log(result);
        },
        error: function (e) {
            console.log("ERROR: ", e);
        }

    });
}

If this seems confusing, I access the fields you can see in my question by
title.name, title.link, title.titleProp.description, etc, inside function (i, title)'s body.

For the HTML,

<label for="moviename" style="margin-right:5px">Title:</label>
<input type="text" class="form-control" id="moviename" placeholder="Enter a title"/>

Where moviename is the variable name you get from the input.

Now, on the backend, we have to configure our path

@PostMapping("/MYURL")
public ResponseEntity<Object> addSearch(@RequestBody SearchCriteria searchCriteria)
        throws IOException {
     // do whatever you want to get a result. I used a custom class "SearchCriteria"
     // which has a getter and a setter for the field
     // **private String moviename;**
    return ResponseEntity.ok(THIS GETS SENT TO AJAX);
}

The main problem was that I have web.security, and you have two choices. First one, you disabling csrf. You have to add this line to your security config.

http.csrf().disable();

in protected void configure(HttpSecurity http) method.

Or, you add csrf to the ajax request. More info on this topic was discussed here

英文:

I am coming with an answer to my question. I managed to get the result I wanted using Ajax, as SnakeDoc suggested. It was a long road, mostly because even if I had a working code, I spent a few hours searching for the Forbidden 403 error on ajax post request.

So, for the js part:

    function ajaxPost() {
        // Here we prepare data for the JSON
        var formData = {
            moviename: $(&quot;#moviename&quot;).val()
        }
        $.ajax({
            type: &quot;POST&quot;,
            contentType: &quot;application/json&quot;,
            url: &quot;MYURL&quot;,
            data: JSON.stringify(formData),
            dataType: &#39;json&#39;,
            success: function (result) {
                {
                    $.each(result,
                        function (i, title) {
                            // do whatever you want with what you got from the server
                        });
                    console.log(&quot;Success: &quot;, result);
                }
                console.log(result);
            },
            error: function (e) {
                console.log(&quot;ERROR: &quot;, e);
            }

        });
    }

If this seems confusing, I access the fields you can see in my question by
title.name, title.link, title.titleProp.description, etc, inside function (i, title)'s body.
For the HTML,

        &lt;label for=&quot;moviename&quot; style=&quot;margin-right:5px&quot;&gt;Title:&lt;/label&gt;
        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;moviename&quot; placeholder=&quot;Enter a title&quot;/&gt;

Where moviename is the variable name you get from the input.

Now, on the backend, we have to configure our path

    @PostMapping(&quot;/MYURL&quot;)
public ResponseEntity&lt;Object&gt; addSearch(@RequestBody SearchCriteria searchCriteria)
        throws IOException {
     // do whatever you want to get a result. I used a custom class &quot;SearchCriteria&quot;
     // which has a getter and a setter for the field
     // **private String moviename;**
    return ResponseEntity.ok(THIS GETS SENT TO AJAX);
}

The main problem was that I have web.security, and you have two choices. First one, you disabling csrf. You have to add this line to your security config.

    http.csrf().disable();

in protected void configure(HttpSecurity http) method.

Or, you add csrf to the ajax request. More info on this topic was discussed here

答案2

得分: 1

使用Thymeleaf,你可以在HTML中像这样显示一个列表:

<tr th:each="student: ${students}">
    <td th:text="${student.id}" />
    <td th:text="${student.name}" />
</tr>

更多信息:https://www.baeldung.com/thymeleaf-iteration

英文:

With thymeleaf, you can display a list in html like so:

&lt;tr th:each=&quot;student: ${students}&quot;&gt;
    &lt;td th:text=&quot;${student.id}&quot; /&gt;
    &lt;td th:text=&quot;${student.name}&quot; /&gt;
&lt;/tr&gt;

More info: https://www.baeldung.com/thymeleaf-iteration

huangapple
  • 本文由 发表于 2020年7月23日 04:33:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63042770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定