I have to show the data form my database to an HTML view like a dropdown menu for that I have created an enitiy, controller and a repository packages.
moreover, I have a dedicated MySql database ready for that I have used the application properties.
CONTROLLER CLASS
import package com.data.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.data.Entity.Location;
import com.data.repository.LocationRepository;
@Controller
public class LocationController {
@Autowired
private LocationRepository locRepo;
@GetMapping("/")
public String home( Model m) {
List<Location> list = locRepo.findAll();
m.addAttribute("all_places", list);
return "index";
}
}
HTML PAGE
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<select th: each="p: ${all_places}">
<option th:text="${p.name}"></option>
</select>
</body>
</html>
ENTITY CLASS
package com.data.Entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "location_dtls")
public class Location {
@Id
@GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY)
private long id;
@Column(name = "place_name")
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Location [id=" id ", name=" name "]";
}
}
REPOSITORY CLASS
package com.data.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.data.Entity.Location;
public interface LocationRepository extends JpaRepository<Location, Long> {
}
ERROR Caused by: java.lang.IllegalArgumentException: Attribute name cannot be null or empty
CodePudding user response:
In your template, you have a space between th:
and each
, which I guess Thymeleaf chokes on.
CodePudding user response:
There is a problem in your index.html
<select>
<option th:each="p:${all_places}" th:value="${p.name}" th:text="${p.name}"></option>
</select>
this will resolve the issue