Search code examples
javaspringthymeleaf

I have trouble with th:if in spring


So I started study java + Spring and i have a problem with "th:if". When i want to print on localhost:8080/car YearOfProduction = 2000 and I use th:info="${info} == '2000'" in my templates it's nothing happens but when i remove th:info="${info} == '2000'" everything works ok, it means when i write for example 1999 in YearOfProduction my app print on localhost year which i wrote.

My controller class:

@Controller public class CarCotnroller {

@RequestMapping(value = "/car", method = RequestMethod.POST)

public String carPost(@ModelAttribute("carForm") CarForm form, Model model) {

    model.addAttribute("info", "Rok produkcji samochodu to: " + form.getYearOfProduction());

    return "cars";
}


@RequestMapping(value = "/car", method = RequestMethod.GET)
public String carPost(Model model) {
    model.addAttribute("carForm", new CarForm());
    return "car";
}

}

My Form class:

public class CarForm {

private String carname;
private String yearOfProduction;

public CarForm(String carname, String yearOfProduction) {
    this.carname = carname;
    this.yearOfProduction = yearOfProduction;
}

public CarForm() {

}

public String getCarname() {
    return carname;
}

public void setCarname(String carname) {
    this.carname = carname;
}

public String getYearOfProduction() {
    return yearOfProduction;
}

public void setYearOfProduction(String yearOfProduction) {
    this.yearOfProduction = yearOfProduction;
}

}

and my templates:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>

    <title>Title</title>
</head>
<body>

<center><span th:if="${info} == '2000'" th:text="${info}"></span></center>
</br></br>
<form th:action="@{/car}" method="post" th:object="${carForm}">
    Car name: <input type="text" th:field="*{carname}">
    <p></p>
    year of production: <input type="text" th:field="*{yearOfProduction}">
    <p></p>

    <input type="submit" value="send">
</form>


</body>
</html>


Solution

  • I still don't know why it isn't work but i make it an another way I wrote in CarController:

    model.addAttribute("info", form.getYearOfProduction() == 2000 ? form.getYearOfProduction(): "Error"); 
    

    and it's work great. Thank you for everything :)