我正在制作一个网站,该网站会像一个模拟Pokédex的地方,并且我试图获得它,以便为Pokémon提供一个页面,该页面会根据可能的下拉列表进行更新神奇宝贝,点击该按钮后,无论选择哪个神奇宝贝,页面都会更新。
我当前面临的问题是,尽管数据库中存在很多神奇宝贝,但下拉列表并未出现,这表明它没有选择正确的值,或者确实是,但是可以。不能正确解释结果。
带有下拉菜单的html是:
<section class="dropdown">
<form action="/pokemon" method="post" th:object="${pokemon}">
<select th:each="pokemon : ${pokemonList}">
<option th:value="${pokemon.dexNum}" th:text="${pokemon.name}"></option>
</select>
</form>
</section>
应该在选择时要求使用此方法,但是如果没有下拉菜单,我无法确认该方法的工作原理,因此可能存在缺陷。
private EntityManager em = new EntityManager();
@PostMapping(value = "/pokemon")
public Pokemon changeCurrentPokemon(int num) {
pokemonService.setCurrentPokemon(em.find(Pokemon.class, num));
return pokemonService.getCurrentPokemon();
}
通过以下方式访问变量:
@GetMapping(value = "/pokemon")
public ModelAndView showPokemon() {
return new ModelAndView("pokemon", "pokemon",
pokemonService.getCurrentPokemon() != null
? pokemonService.getCurrentPokemon()
: new Pokemon(1, "Bulbasaur", "Seed Pokemon", "/images/pokemon/1-Bulbasaur.png", "Grass", "Poison")
);
}
pokemonService类是此处显示的pokemonService的实现:
package pokedex.services;
import org.springframework.stereotype.Service;
import pokedex.dao.PokemonRepository;
import pokedex.entities.Pokemon;
import java.util.List;
@Service
public class PokemonServiceImpl implements PokemonService {
private PokemonRepository pokemonRepository;
private Pokemon currentPokemon;
public PokemonServiceImpl(PokemonRepository pokemonRepository) {
this.pokemonRepository = pokemonRepository;
}
@Override
public List<Pokemon> getPokemonList() {
return pokemonRepository.findAll();
}
@Override
public void addPokemon(Pokemon pokemon) {
currentPokemon = pokemon;
pokemonRepository.save(pokemon);
}
@Override
public void setCurrentPokemon(Pokemon pokemon) {
currentPokemon = pokemon;
}
@Override
public Pokemon getCurrentPokemon() {
return currentPokemon;
}
@Override
public int getNumberOfPokemon() {
return (int) pokemonRepository.count();
}
}
如果有人对如何完成表格有任何提示,我将非常感谢您的帮助,谢谢
答案 0 :(得分:0)
您在pokemon
中有一个pokemon
模型变量和一个th:each
变量。更改其中之一。也未设置pokemonList
。不只是错字吗?
<section class="dropdown">
<form action="/pokemon" method="post" th:object="${pokemon}">
<select th:each="pokemon: ${pokemonList}">
<option th:value="${pokemon.dexNum}" th:text="${pokemon.name}"></option>
</select>
</form>
</section>