Thymeleaf / Spring. get property key from ModelMap - java

I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
in my property file:
signup.form.error.email.already.exists=Email (already taken)
in my controller:
protected static final String ERROR_MESSAGE_KEY = "errorMessageKey";
model.addAttribute(ERROR_MESSAGE_KEY, "signup.form.error.email.already.exists");
in the template:
<div th:if="${errorMessageKey != null}" class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#{errorMessageKey}" />
</div>
But this is what I see inthe template instead of Email (already taken)
??errorMessageKey_en_US??

Try using
<p th:text="#{signup.form.error.email.already.exists}" />
When you code this:
model.addAttribute(ERROR_MESSAGE_KEY, "signup.form.error.email.already.exists");
Spring is not resolving the message from the message.properties file: you are simply putting the string "signup.form.error.email.already.exists" in the model...
NOTE the expression #{errorMessageKey} is returning the name of the source file containing the specified message.

Putting properties to Model is not how you resolve the properties in Thymeleaf. See the docs where they explain how to do it properly.

It is because of Thymeleaf is trying to fetch locale message. And by default it is trying en_US.
You can look at this answer

Related

How to display data from object in zk (zul file)?

I am using zk framework for my internship. I currently have a controller that goes and fetches a special link from an api and I have to create an IFrame in a zul file and bind this link into this iframe.
I do not know how to dynamically bind data either from an object, a modal or a properties file.
<div id="iframe-div" height="100%" style="background: #ccc;">
<iframe id="iframe" width="100%" height="100%" src="https://thisIsTheLink.com"/>
</div>
is there something similar as src="{mylink}" in zk as they do in other front end frameworks? Is it possible to dynamically bind data in zk framework?
Yes it is possible. I recommend using MVVM binding.
zul file:
<window viewModel="#id('vm') #init('com.example.IndexVM')">
<div id="iframe-div" height="100%" style="background: #ccc;">
<iframe id="iframe" width="100%" height="100%" src="#load(vm.includeSrc)" />
</div>
</window>
view model:
public class IndexVM() {
public String getIncludeSrc() {
return "https://thisIsTheLink.com";
}
}
You can even pass parameters to your included file.

Passing value from controller to html in spring

Hello I have a simple web page where I have a button and a text near to button. I need to change text when button clicked and get the new text from code.
This is controller class from where I need to pass response:
#GetMapping("/stream")
public String openStream(Model model) {
String response = service.openStream();
model.addAttribute("stream", response);
return "mainpage";
}
And here my html page, the value from controller must be instead of question marks:
<div id="container">
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
<p align="center">?????</p>
</div>
Thanks in advance for your help.
Edit:
I tried ${stream}
but getting it as text not value, please see screenshot:
Edit 2:
I need pass String from the text area to doc variable in the controller. Please help.
HTML:
<div>
<textarea rows="10" cols="100" name="description"></textarea>
button class="button" onclick="window.location.href ='/send';">Send</button>
</div>
Controller:
#GetMapping("/send")
public String send(String doc) {
service.sendDoc(doc);
return "mainpage";
}
Change
<p align="center">?????</p>
To
<p align="center">${stream}</p> OR <p th:text="${stream}"></p>
How it is working?
You can access variables value by ${key}.
Example
model.addAttribute("key", value);
Get value by ${key} in HTML
In Thymeleaf, these model attributes (or context variables in
Thymeleaf jargon) can be accessed with the following syntax:
${attributeName}, where attributeName in our case is stream. This
is a Spring EL expression. In short, Spring EL (Spring Expression
Language) is a language that supports querying and manipulating an
object graph at runtime.
UPDATE
The th:field attribute can be used on input, select, or, textarea.
Replace <p align="center">?????</p> with
<input type="text" id="stream" name="stream" th:value="${stream}" />
OR
<input type="text" th:field="*{stream}" />`
OR
<input type="text" id="stream" name="stream" th:field="*{stream}" th:value="${stream}" />
Also try <p th:inline="text">[[${stream}]]</p>; <p data-th-text="${stream}" />
Thymeleaf Document Thymeleaf Document Inputs
UPDATE 2
Get value from Thymeleaf to Spring Boot
<form th:action="#{/send}" method="get">
<textarea th:name="doc" rows="10" cols="100" name="doc"></textarea>
<button type="submit">Send</button>
</form>
#GetMapping("/send")
public String send(#RequestParam(name="doc", required = false) String doc) {
//change required = false as per requirement
System.out.println("Doc: "+doc);
return "textarea-input";
}
Note: use "th:field" for Entity/Model
Thank you for your help. Below shown line helped:
<p th:inline="text">[[${stream}]]</p>
Try these : <p align="center">${stream}</p> or <p th:text="${stream}"></p>
This tag may be causing a problem :
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
Please check it by removing this.
So i solve it like that :
let said i want to pass int ValueIwantToPass=5
in my controller i put
#GetMapping("/tasks")
public String listTasks(Model model) {
model.addAttribute("value", ValueIwantToPass);
}
and in my HTML file it look
<h1>i wanted to pass [[${value}]]</h1>

styles not applied on validation form using thymeleaf and bootstrap

Trying to add text with a style on error validation in a bootstrap form
This is part of the form:
<label th:text="#{name}"
class="col-form-label col-form-label-sm"></label>
<input
type="text" class="form-control form-control-sm"
th:field="*{name}" />
<span
th:if="${#fields.hasErrors('name')}" th:errors="*{name}"
th:class="invalid-feedback">Here there is an error</span>
I get the message on validation error, but without styles.
If I debug I see the class with the style:
<span class="invalid-feedback">Here there is an error</span>
I have tried with severals styles like help-block but no way.
I'm using bootstrap4.0.0-alpha.6
Any idea?
Thanks
In case you are still interested.
Bootstrap's current validation docs give you three approaches: client-side custom validation, browser defaults and server-side validation.
From your post I will assume you're using server side, meaning that you are sending the data to be validated in your server code for then showing the error fields when the form is re-rendered.
In that case, remember that for bootstrap's styles to kick in, a certain html structure is expected from your code, example:
<input th:field ="*{email}" type="email" class="form-control"
th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid"
required>
<div class="invalid-feedback">
<p th:each="error: ${#fields.errors('email')}" th:text="${error}">Invalid data</p>
</div>
(I believe a span tag will work too for <div class="invalid-feedback">)
That is a minimal necessary structure for the error styles to work. What happens:
Initially, invalid-feedback is assigned display: none
The form is submitted, if it has an error it'll be re-rendered and it's up to the developer to provide a mechanism which will include is-invalid in the class attribute of every <input class="form-control"/> with an error. In the previous code, th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid" is responsible for that to happen. (I'm new to Spring and Thymeleaf, so there could be a neater code for this)
Declaration .form-control.is-invalid~.invalid-feedback in _forms.scss will kick in and assign display: block to <div class="invalid-feedback">, thus showing each field's error message (s).
That should be enough to show the error (s) under each field and highlight them in red.
HIH

Thymeleaf gets all images from folders

is it possible to gets all images from folders?
I mean I've images structure like this
folder1 ---
---image1.jpg
---image2.jpg
---image3.jpg
folder2 ---
---image1.jpg
---image2.jpg
how can I display all images in html?
#edit
only my tries:
<p th:each="i: ${#numbers.sequence(1, 5)}">
<img th:src="#{/folder/001/0.jpg}"/>
</p>
There's nothing built-in to Thymeleaf to read a folder and get a list of files in it. If you're trying to build something dynamically (which I'm not sure from your question if that's what you're trying to do), then you'd need to read it in your controller (whatever Java code is putting together the context variable map or model that you're sending to Thymeleaf).
If you're just trying to do a static list of five numbered images, like your example code, then you need to do concatenation of your "each" variable inside an expression to generate your image URL, like this:
<p th:each="i: ${#numbers.sequence(1, 5)}">
<img th:src="#{${'/folder/001/' + i + '.jpg'}}"/>
</p>
That will generate the following HTML:
<p>
<img src="/context/folder/001/1.jpg" />
</p>
<p>
<img src="/context/folder/001/2.jpg" />
</p>
<p>
<img src="/context/folder/001/3.jpg" />
</p>
<p>
<img src="/context/folder/001/4.jpg" />
</p>
<p>
<img src="/context/folder/001/5.jpg" />
</p>
There are more examples of creating Link URLs in the documentation. These show how you can use an expression to construct the base URL or to construct any query arguments (though usually you don't use query arguments when loading images).

How to define a namespace in spring

I've been working local on tomcat server 7, now I uploaded my project to a server but it has tomcat 6. So the following doesn't work:
model.addAttribute("category",cat);
<div class="span4">
<h2>
Category:
<c:out value="${category}" />
</h2>
<br />
<c:forEach items="${categoryList}" var="item">
<div class="alert alert-init">
<c:url value="/getInit/${item.getiID()}" var="url" />
<c:out value="${item.getTitle()}" />
</div>
</c:forEach>
</div>
It gives me following error code:
org.apache.jasper.JasperException: /WEB-INF/views/categoryinitiatives.jsp(34,5) The function iIDGetter must be used with a prefix when a default namespace is not specified
I've been searching all over the web to find a solution for this problem, but without success. Does anyone know how to fix this?
If you wanna access a property of a bean using EL, just write item.title instead of item.getTitle(). It will automatically call the getter and probably solve your problem.
Moreover, item.getiID() isn't a valid name. If you have a property iID in your bean, you have to name the getter getIID() to access it using EL. Have a look at the lowerCamelCase syntax.

Categories