Home > other >  How to solve thymeleaf template parsing error
How to solve thymeleaf template parsing error

Time:05-07

I'm trying to present a html to screen but I'm getting template parser error from thymeleaf. Here is my code and error:

index.html:

<body>
    <h2>My ToDo List</h2>
    <form action="/send-form-data" method="post" th:object="${myForm}">
    <table>
        <tr>
            <td>Title:</td>
            <td><input type="text" th:field="*{title}"/></td>
        </tr>
        <tr>
            <td>Decription:</td>
            <td><input type="text" th:field="*{description}"/></td>
            </tr>
    </table>
controller:
@Controller
public class TodolistController {

@RequestMapping(value = { "/display-form", "/index.html" }, method = RequestMethod.GET)
public ModelAndView displayForm() {
    ModelAndView mv = new ModelAndView("index");
    mv.addObject("myForm", new MyModel());

    return mv;
}

}

MyModel:

public class MyModel {

private String title;
private String description;

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}

}

Error:

Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 15, col 28)

Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'formData' available as request attribute

I tried something but not helped. When I delete the inputs from HTML it works finely so problem is about matching thymeleaf fields with MyModel variables but I couldn't solve.

CodePudding user response:

I have tried your program, and I consider that you typed wrong url in your browser. Because there is nothing wrong in your code.

According to your controller:

@RequestMapping(value = { "/display-form", "/index.html" }, method = RequestMethod.GET)

please make sure your browser's url is:

<host>:<port>/<context-path>/index.html or <host>:<port>/<context-path>/display-form

instead of <host>:<port>/<context-path>/.

Then you will see expected page:

enter image description here

CodePudding user response:

Just from the error message I would assume the target object you want to fill is missing or the way you currently provide it does not work. You can adjust your controller method to look like

@Controller
public class TodolistController {

@RequestMapping(value = { "/display-form", "/index.html" }, method = RequestMethod.GET)
public String displayForm(Model model) {
    model.addAttribute("myForm", new MyModel());
    return "index";
}

Assuming your index.html is located in resources/templates

  • Related