使用Spring-mvc和thymeleaf从实体填充下拉列表

时间:2019-05-18 18:28:27

标签: java spring-mvc thymeleaf

我正在开发一个应用程序,其中我想使用表格中的下拉菜单将一名学生添加到一餐中。我的代码如下:

Meal.java

@Entity
public class Meal {

@Id
@GeneratedValue
  private Long id;

  @OneToOne
  private Student mealCook;

  private String mealName;

  private int mealPrice;

Student.java

@Entity
 public class Student {

@Id
@GeneratedValue
private Long id;

private String studentName;

MealController.java

@Controller
@RequestMapping("/m")
public class MealController {

private final MealRepository mealRepository;
private final StudentRepository studentRepository;

public MealController(MealRepository mealRepository, StudentRepository studentRepository){
    this.mealRepository = mealRepository;
    this.studentRepository = studentRepository;
}

@GetMapping
public ModelAndView list(){
    Iterable<Meal> meals = this.mealRepository.findAll();
    return new ModelAndView("meals/list" , "meals", meals);
}

@GetMapping("{id}")
public ModelAndView view(@PathVariable("id") Meal meal) {
    return new ModelAndView("meals/view", "meal", meal);
}

@GetMapping(params = "form")
public String createForm(@ModelAttribute Meal meal) {
    return "meals/form";
}

@PostMapping
public ModelAndView create(@Valid Meal meal,  BindingResult result,
                           RedirectAttributes redirect) {
    Iterable<Student> students = this.studentRepository.findAll();
    if (result.hasErrors()) {
        return new ModelAndView("meals/form", "formErrors", result.getAllErrors());
    }
    meal = this.mealRepository.save(meal);
    redirect.addFlashAttribute("globalMessage", "view.success");
    return new ModelAndView("redirect:/m/{meal.id}", "meal.id", meal.getId());
}

最后我的观点-> form.html

<form id="mealForm" th:action="@{/m/(form)}" th:object="${meal}" action="#" method="post">

    <div class="form-group">
        <label for="mealName">Meal Name</label>
        <input type="text" th:field="*{mealName}" th:class="${'form-control' + (#fields.hasErrors('mealName') ? ' is-invalid' : '')}">
    </div>

    <div class="form-group">
        <label for="mealCook">Meal Cook</label>
        <select th:field="*{mealCook}">
            <option th:each= ??
                    th:value= ??
                    th:text= ??</option>
        </select>
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

现在的目标是通过从表单的下拉菜单中选择“ studentName”,将一名学生添加到一顿饭中。

但是我在努力如何将学生列表从控制器传递到视图并将其显示在下拉列表中。

2 个答案:

答案 0 :(得分:1)

您应该在打开表单的任何位置的控制器中添加学生列表

    ModelAndView model = new ModelAndView("studentList");
    model.addObject(students) // get list from database or...
    // students =studentRepository.findAll() or use your exclusive query

还有<option>

<option th:each="item : ${studentList}"
        th:value=${item.id} // value you want...
        th:text=${item.name}>
</option>

并更改实体:

Meal.java

@Entity
    public class Meal {

@Id
@GeneratedValue
  private Long id;

  @OneToOne
  @JoinColumn(name = "meel_cook_id")
  private Student mealCook;

  private String mealName;

  private int mealPrice;

Student.java

@Entity
 public class Student {

@Id
@GeneratedValue
private Long id;

private String studentName;

@OneToOne(mappedBy = "mealCook")
@JsonBackReference
private Meal meal;

答案 1 :(得分:1)

将学生列表作为属性传递给控制器​​中的模型。 例如,

@GetMapping(params = "form")
public String createForm(@ModelAttribute Meal meal, Model theModel) {
    theModel.addAttribute("students", studentRepository.findAll());

    return "meals/form";
}

然后,您可以使用命令读取此属性。

<option th:each="student:${students}"
                    th:value="${student.studentName}"
                    th:text="${student.studentName}">

</option>