如何使用Spring Boot,JPA和Thymeleaf设置搜索栏

时间:2019-02-01 14:11:25

标签: java spring search thymeleaf

因此,我有一个Spring Web应用程序,这是一个用于输入课程,讲师等的简单表格。现在,我需要一个用于这些课程的简单搜索栏,它将返回与课程主题相匹配的结果。

这是我的代码,也是我到目前为止所做的。

Lecture.java

@Data
@Entity
@Table(name="Lecture")
@NoArgsConstructor
public class Lectureimplements Serializable {

    private static final long serialVersionUID = 1L;

    @Valid
    @OneToOne(targetEntity=Lecturer.class, cascade=CascadeType.ALL)
    @JoinTable(
        name="Lecture_Lecturer",
        joinColumns = @JoinColumn(name = "lecture"),
        inverseJoinColumns = @JoinColumn(name = "lecturer"))
    private Lecturer lecturer;

    @NotEmpty(message = "Subject is empty!")
    @Size(min = 2, max = 50, message = "Subject must be from 2 to 50 letters long!")
    @Column(name="subject")
    private String subject;

    @NotEmpty(message = "You haven't entered a short description!")
    @Size(min = 2, max = 150, message = "A short description must be from 2 to 150 letters long!")
    @Column(name="description")
    private String shortDescription;

    @NotNull(message = "You haven't picked a lecture type!")
    @Column(name="type")
    @Enumerated(EnumType.STRING)
    private LectureType lectureType;

    @Column(name="published")
    private Boolean published;

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name="creationDate")
    private Date creationDate;


    public enum LectureType {

        PRACTICE, PRESENTATION
    }
}

LectureController.java

@Slf4j
@Controller
@RequestMapping
@SessionAttributes({"types", "positions", "lectureList", "published"})
public class LectureController {

    @Autowired
    LectureRepository lectureR;

    @Autowired
    LecturerRepository lecturerR;

    List<Lecture> lectureList = new ArrayList<>();

    @RequestMapping
    public String newLecture() {

        return "newLecture";
    }

    @GetMapping("/newLecture")
    public String showForm(Model model, Lecture lecture) {

        log.info("Filling data to show form.");

        model.addAttribute("lecture", new Lecture());
        model.addAttribute("types", Lecture.LectureType.values());
        model.addAttribute("positions", Lecturer.LecturerPositions.values());
        model.addAttribute("published", lecture.getPublished());

        return "newLecture";
    }

    @GetMapping("/allLectures")
    public String showLectures() {

        return "allLectures";
    }

    @GetMapping("/resetCounter")
    public String /resetCounter(SessionStatus status) {

        lectureList.clear();
        status.setComplete();
        return "redirect:/newLecture";
    }

    @PostMapping("/novoPredavanje")
    public String processForm(@Valid Lecture lecture, Errors errors, Model model) {

    log.info("Processing lecture: " + lecture);

    if(errors.hasErrors()) {

        log.info("Lecture has errors. Ending.");

        return "newLecture";

    } else {

        lectureList.add(lecture);

        model.addAttribute("numberOfLectures", lectureList.size());

        model.addAttribute("lecture", lecture);

        model.addAttribute("published", lecture.getPublished());

        model.addAttribute("lectureList", lectureList);

        log.info("Lecture successfully saved: " + lecture);

        return "output";
    }
}

    @GetMapping("/lectureSearch")
    public String lectureSearch(Model model) {

        model.addAttribute("lecture", new Lecture());

        return "lectureSearch";
    }

    @PostMapping("/lectureSearch")
    public String lectureSearch(Lecture lecture, Model model, String subject) {

        List<Lecture> foundLectures = lectureR.findBySubject(subject);
        model.addAttribute("foundLectures", foundLectures);

        return "lectureSearch";
    }
}

LectureRepository.java

@Repository
public interface LectureRepository extends CrudRepository<Lecture, Long> {

    List<Lecture> findBySubject(String subject);
}

lectureSearch.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" >
        <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}" >
        <title>Lecture output</title>
    </head>
    <body>
        <img th:src="@{~/images/picture.png}" />

        <form action="/resetCounter">
            <input type="submit" value="Reset counter" class="btn btn-warning" style="background-color: orange"/>
        </form>

        <div sec:authorize="isAuthenticated()">
            <a th:href="@{/newLecture}" class="btn btn-primary">Enter a new lecture</a>
            <a th:href="@{/svaPredavanja}" class="btn btn-primary">All lectures</a>
            <a th:href="@{/pretragaPredavanja}" class="btn btn-primary">Lecture search</a>
        </div>

        <div sec:authorize="isAuthenticated()">
            <form method="POST" th:action="@{/logout}">You are logged in as <span sec:authentication="name">User</span>.
                <input type="submit" value="Logout" class="btn btn-danger" />
            </form>
        </div>

        <div><h3>Lecture search</h3></div>
        <form th:object="${lecture}" method="post">
            <div>
                <label for="subject">Subject: </label>
                <input type="text" name="lectureSearch" th:value="${lectureSearch}">
                <input type="submit" value="Search">
            </div>
        </form>

        <table>
            <tr>
                <th>Subject</th>
                <th>Short description</th>
                <th>Lecture Type</th>
                <th>Lecturer's Name</th>
                <th>Lecturer's position</th>
                <th>Published</th>
            </tr>
            <tr th:each="lecture : ${lectureSearch}">
                <td><span th:text="${lecture.subject}" >LECTURE.SUBJECT</span></td>
                <td><span th:text="${lecture.shortDescription}" >LECTURE.SHORTDESCRIPTION</span></td>
                <td><span th:text="${lecture.lectureType}" >LECTURE.LECTURETYPE</span></td>
                <td><span th:text="${lecture.lecturer.name}" >LECTURER.NAME</span></td>
                <td><span th:text="${lecture.lecturer.lecturerPosition}" >LECTURER.LECTURERPOSITION</span></td>
                <td><span th:text="${lecture.published}" >LECTURE.PUBLISHED</span></td>
            </tr>

        </table>

</body>
</html>

在搜索栏中输入主题后,即使存在关于所查询主题的演讲,也看不到任何结果。检入调试器后,即使用户输入了他要搜索的主题,变量subject仍为null。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您的模板中有

<tr th:each="lecture : ${lectureSearch}">

但是您要添加到模型中

 model.addAttribute("foundLectures", foundLectures);

所以您的桌子应该是

<tr th:each="lecture : ${foundLectures}">

此外,表单输入字段的绑定错误。 应该是

<form th:object="${lecture}" method="post">
   <div>
       <label for="subject">Subject: </label>
       <input type="text" name="subject" th:field="*{subject}">
       <input type="submit" value="Search">
   </div>
</form>

有关更多信息,请阅读手册:https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html