-1

Project Directory Structure

I'm new to Thymeleaf. It's a simple HelloWorld app in which I want to display the model message returned from controller. It's running successfully but it's not displaying the message returned from controller.
But when the same code is running with a given jsp file it's reading which is a common thing.

WelcomeController class is

@Controller
public class WelcomeController {
    private String pass="Welcome To ThymLeaf";

    @RequestMapping(value="/")
    public String welcomeUser(Map<String,String> model) {
        model.put("message", pass);
        return "index";
    }
}

My index.html is

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>ThymLeaf Demo</title>
<link rel="stylesheet" th:href="@{/main.css}" href="../../main.css">
</head>
<body>
    <div class="container">
        <h1>Spring Boot Using ThymLeaf</h1>
        <h2>
            <span th:if="${message != null}"
                th:text="'Message:' + ${message}">> 
            </span>
        </h2>
    </div>
</body>
</html>


It's displaying Spring Boot Using ThymLeaf but not the message attribute because it is coming with a null value but why?

Avijit Barua
  • 2,950
  • 5
  • 14
  • 35
Stone
  • 33
  • 9
  • but it's EL how can i miss $ and the problem is it's coming with a **null** that's why it's not showing the **Message:** – Stone Jul 20 '18 at 09:59
  • I dont know what gets passed to your function when you specify the Parameter as Map model, but you usually use Model, ModelMap or ModelAndView. With those this code should work. Is there any reason why you use Map? – espendennis Jul 20 '18 at 10:41
  • @espendennis that's also valid Spring code and doesn't make a difference in html-tempates (Thymleaf, jsp, EL, ect.). – Flocke Jul 20 '18 at 11:18
  • yes and the problem lies on **${ message }** it's not reading the data within the model attribute is it the way we access model data in thymleaf – Stone Jul 20 '18 at 15:25
  • View the source in your browser and make sure it's actually interpreting the file it as Thymeleaf. – Metroids Jul 20 '18 at 18:09
  • Solved your problem ? @Stone – Avijit Barua Jul 23 '18 at 08:12

2 Answers2

0

You can check this answer

<span th:if="${message} != null">
  <span th:text= "'Message:' + ${message}"></span>
</span>
Avijit Barua
  • 2,950
  • 5
  • 14
  • 35
0

Your not- null check is not correct here , do something like this :--

<span th:if="${message} != null or ${message} !=  '' ">
  <span th:text= "${message}"></span>
</span>


PS:- make sure you're putting commas correctly otherwise your page will end up with error.

Sumit
  • 917
  • 1
  • 7
  • 18