ThymeLeaf не печатает значения списка

#javascript #jquery #spring-mvc #thymeleaf

Вопрос:

У меня есть следующий html:

 <html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Sightings</title>
  </head>
<body>

    <div class="container">
                <div class="row m-4">
                <div class="col text-center border border-dark">
                    <h1><a href="/" class="text-dark">Sightings Manager</a></h1>
                </div>
            </div>
            <div class="row m-4 border border-dark">
                <div class="col text-center m-3">
                    <a href="heroes" class="btn btn-outline-primary btn-lg">Heroes</a>
                </div>

                <div class="col text-center m-3">
                    <a href="" class="btn btn-outline-primary btn-lg">Organizations</a>
                </div>

                <div class="col text-center m-3">
                    <a href="locations" class="btn btn-outline-primary btn-lg">Locations</a>
                </div>
                <div class="col text-center m-3">
                    <a href="sightings" class="btn btn-outline-primary btn-lg">Sightings</a>

                </div>
               
                
            </div>
              <div class="row m-4 border border-dark">
               <div class="col text-left border border-dark">
              <input type="radio" id="selectByDate" name="selectOption" value="selectByDate">
              <label for="selectByDate">Sightings By Date</label><br>

              <input type="radio" id="selectByHero" name="selectOption" value="selectByHero">
              <label for="selectByHero">Sightings by Hero</label>

              
              <div class="col text-center" id="date" style="display:none;">
              <form action="getLocationsByDate" method="GET">
              <select id="chooseDate" name="chooseDate">
              <option selected disabled>Choose a date</option>
              </select>
              <input type="submit" value="View Locations">
              </form>
              </div>
              <!-- Other div to go here with other form -->
              </div>
            </div>
              
            <div class="row m-4 border border-dark">
                <div class="col text-center m-3">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Address</th>
                                <th>Latitude</th>
                                <th>Longitude</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:each="location : ${locations}">
                                <td th:text="${location.id}">Location ID</td>
                                <td th:text='${location.name}'>Location Name</td>
                                <td th:text="${location.address}">Location Address</td>
                                <td th:text="${location.latitude}">Location Latitude</td>
                                <td th:text="${location.longitude}">Location Longitude</td>

                                
          
                             
                            </tr>
    
                        </tbody>
                    </table>
                </div>
            
            
            </div>
            
            
            
            </div>
 <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
 <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft 2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704 h835Lr 6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script src="sightings.js"></script>
</body>
</html> 

А также следующий javascript:

 $(document).ready(selectOption);

function selectOption()
{
    $('input:radio[name="selectOption"]').change(function()
                                        {
                                            if($(this).val() == "selectByDate")
                                            {
                                                $("#date").show();
                                                $.ajax({
                                                    type:"GET",
                                                    url:"http://localhost:8080/getDates",
                                                    success: function(dates)
                                                    {
                                                        console.log(dates.length);
                                                        for(let i=0;i<dates.length;i  )
                                                        {
                                                                    optionText=dates[i];
                                                                    optionValue=dates[i];
                                                                    $("#chooseDate").append(new Option(optionText,optionValue));
                                                        }
                                                        //if viewlocations has been clicked
                                        
                                                    }
                                                    
                                                    
                                                });
                                                
                                                
                                            }
                                            else if($(this).val() == "selectByHero")
                                            {
                                                $('#chooseDate')
                                                    .empty()
                                                    .append('<option selected disabled>Choose a date</option>'); //remove all data as will stack on top of each other
                                                $("#date").hide();
                                            }
                                        });
} 

Both are run via a controller in spring mvc:

 @Controller
public class SightingsController 
{
@Autowired
HeroDAO heroDao;

@Autowired
LocationDao locationDao;


@GetMapping("sightings")
public String displayLocations()
{
    return "sightings";
    
}
@GetMapping(value="getDates",produces="application/json")
@ResponseBody
public List<LocalDate> getDates()//returns all dates of herosightings and adds it to model
{
    List<Sighting> sightings = locationDao.getAllSightings();
    List<LocalDate> dates = new ArrayList<LocalDate>();
    
    for(int i=0;i<sightings.size();i  )
    {
        dates.add(sightings.get(i).getDate());
    }
    return dates;
}
@GetMapping("getLocationsByDate")
public String getLocationsByDate(HttpServletRequest request,Model model)
{
    String date =request.getParameter("chooseDate");
    LocalDate localDate = LocalDate.parse(date);
    List<Location> locations = locationDao.sightingsOnDate(localDate);
    model.addAttribute("locations",locations);
    return "redirect:/sightings";
    
}
 

Мой javascript выполняет заполнение поля выбора с помощью вызова ajax в общедоступный список контроллеров getDates (), который возвращает список дат и добавляет его в html . Затем пользователь выбирает один из этих элементов и снова отправляет его контроллеру в общедоступную строку getLocationsByDate(запрос HttpServletRequest,модель модели). Предполагается, что эта функция добавит модель в нижнюю часть страницы(в теле) и распечатает все результаты. Моя проблема в том, что лист thymeleaf, похоже, вообще не считывает значения(nothng появляется в теле). Я знаю, что значения, отправленные в /getLocationsByDate, и значения, полученные с помощью List locations=LocationDAO.sightingsOnDate(LocalDate); верны, однако выполнение атрибута .AddAttribute, похоже, ничего не значит на html-странице. Любая помощь будет признательна, и я надеюсь, что это не какая-то синтаксическая ошибка.

Редактировать: Также, если нужно посмотреть, что находится в объекте местоположения:

 public class Location 
{
private int id;
private String name;
private String description;
private String address;
private String latitude;
private String longitude;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public String getLatitude() {
    return latitude;
}
public void setLatitude(String latitude) {
    this.latitude = latitude;
}
public String getLongitude() {
    return longitude;
}
public void setLongitude(String longitude) {
    this.longitude = longitude;
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result   ((address == null) ? 0 : address.hashCode());
    result = prime * result   ((description == null) ? 0 : description.hashCode());
    result = prime * result   id;
    result = prime * result   ((latitude == null) ? 0 : latitude.hashCode());
    result = prime * result   ((longitude == null) ? 0 : longitude.hashCode());
    result = prime * result   ((name == null) ? 0 : name.hashCode());
    return resu<
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Location other = (Location) obj;
    if (address == null) {
        if (other.address != null)
            return false;
    } else if (!address.equals(other.address))
        return false;
    if (description == null) {
        if (other.description != null)
            return false;
    } else if (!description.equals(other.description))
        return false;
    if (id != other.id)
        return false;
    if (latitude == null) {
        if (other.latitude != null)
            return false;
    } else if (!latitude.equals(other.latitude))
        return false;
    if (longitude == null) {
        if (other.longitude != null)
            return false;
    } else if (!longitude.equals(other.longitude))
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}



}
 

Комментарии:

1. Неважно, что я решил проблему, но я действительно не уверен, почему это вызвало проблему. Я просто вернул html вместо того, чтобы перенаправлять его в контроллере

2. Рекомендуется ответить на свой собственный вопрос, если вы нашли решение.

Ответ №1:

Я решил проблему(хотя я не уверен, почему это решение работает.. потребуется провести дальнейшие исследования). Я вернул html в контроллере, а не использовал перенаправление. Похоже, именно это и было причиной проблемы.