Reputation: 129
I am trying to get a list of objects that are sent to the server from the html form as parameters for my list, then I will loop through those entries and then return them through the springboot th:each
. But it doesn't seem to be working at all. On load the form appears but when I enter a value in it, then it returns an error page and the URL however turns:
http://localhost:8080/@%7B/%7D?%24%7Bcontent%7D=hello
this output in eclipse says:
Expression "content" is not valid: only variable expressions ${...} or selection expressions *{...} are allowed in Spring field bindings
Note: content here is the value property in my form. My controller looks like this:
@Controller
public HelloList() {
this.addUs = new ArrayList <>();
}
@RequestMapping("/")
public String getlist(@RequestParam (required = false) String content, Model model) {
if (content != null && !content.trim().isEmpty()) {
this.addUs.add(content);
}
model.addAttribute("list",addUs);
return "index";
}
the index.html looks like this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
</head>
<body>
<div>
<ul>
<li th:each="amHere: ${addUs}">
<span th:text="${amHere}">hello! world</span>
</li>
</ul>
<form action="@{/}" method="GET">
<input type="text" name="content"/>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
</html>
This might be a duplicate but it seems like most of the solutions I came across are not helping. So any help is mostly appreciated. Thank you in advance.
Upvotes: 1
Views: 882
Reputation: 129
Turns out I was missing the initialization of my list in the constructor. I initialized the list by adding a value to it first in the constructor like this.
this.addUs.add("Hello World");
Because the @RequestMapping
is mapped to the home path in my case index.html, any request gets sent there automatically.
working example
Upvotes: 1
Reputation: 20487
action = "@{/}"
should be th:action="@{/}"
. That's the reason you're seeing the weird url (because it's url encoding @{/}
). Thymeleaf only evaluates expressions that start with th:
.
I'm not sure about the other error. It looks like the html you've pasted doesn't match up with the error you are getting.
If you urldecode http://localhost:8080/@%7B/%7D?%24%7Bcontent%7D=hello
, you get http://localhost:8080/@{/}?${content}=hello
, which doesn't line up with your form.
Upvotes: 0