Java 如何使用springboot、JPA和Thymeleaf设置搜索栏

Java 如何使用springboot、JPA和Thymeleaf设置搜索栏,java,spring,search,thymeleaf,Java,Spring,Search,Thymeleaf,所以,我有一个SpringWeb应用程序,它是一个进入课堂、讲师等的简单形式。。。现在我需要一个简单的搜索栏来搜索这些类,它将返回与类主题匹配的结果 这是我的代码,也是我到目前为止所做的 touch.java @Data @Entity @Table(name="Lecture") @NoArgsConstructor public class Lectureimplements Serializable { private static final long serialVersio

所以,我有一个SpringWeb应用程序,它是一个进入课堂、讲师等的简单形式。。。现在我需要一个简单的搜索栏来搜索这些类,它将返回与类主题匹配的结果

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

touch.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
    }
}
讲师控制器.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";
    }
}
@Slf4j
@控制器
@请求映射
@会期贡献({“类型”、“职位”、“讲师”、“已发表”})
公共课讲师{
@自动连线
讲师兼讲师;
@自动连线
讲师,代理讲师;
List讲师列表=新建ArrayList();
@请求映射
公共字符串{
返回“新讲座”;
}
@GetMapping(“/newtouch”)
公共字符串展示形式(模型、讲座){
log.info(“填写数据以显示表单”);
model.addAttribute(“讲座”,新讲座());
model.addAttribute(“types”,touch.touchtype.values());
model.addAttribute(“positions”,讲师.讲师职位.values());
model.addAttribute(“published”,touch.getPublished());
返回“新讲座”;
}
@GetMapping(“/AllMapping”)
公共字符串{
返回“所有讲座”;
}
@GetMapping(“/resetCounter”)
公共字符串/重置计数器(会话状态){
讲师:clear();
status.setComplete();
返回“重定向:/newtouch”;
}
@邮戳(“/novoPredavanje”)
公共字符串processForm(@Valid-touch-touch,Errors-Errors,Model){
log.info(“处理讲座:”+讲座);
if(errors.hasErrors()){
log.info(“讲座有错误。结束”);
返回“新讲座”;
}否则{
讲师列表。添加(讲师);
model.addAttribute(“NumberOfExpertions”,讲师列表.size());
model.addAttribute(“讲座”,讲座);
model.addAttribute(“published”,touch.getPublished());
model.addAttribute(“讲师列表”,讲师列表);
log.info(“讲座成功保存:+讲座”);
返回“输出”;
}
}
@GetMapping(“/讲师搜索”)
公共字符串讲师搜索(模型){
model.addAttribute(“讲座”,新讲座());
返回“讲师搜索”;
}
@后映射(“/讲师搜索”)
公共字符串讲师搜索(讲座、模型、字符串主题){
List FOUNTESSIONS=讲师。findBySubject(主题);
model.addAttribute(“FoundCourts”,FoundCourts);
返回“讲师搜索”;
}
}
讲师职位.java

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

    List<Lecture> findBySubject(String subject);
}
@存储库
公共接口讲师position扩展了crudeposition{
列出findBySubject(字符串主题);
}
讲师搜索.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
也为空。
任何帮助都将不胜感激。

您的模板中包含:

<tr th:each="lecture : ${lectureSearch}">
所以你的桌子应该是

<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>

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

<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>

主题:

有关更多信息,请阅读手册:

仍然无法工作;我相信问题在于搜索时变量
subject
为空,我不知道如何解决这个问题。我为您必须执行的表单添加了修复。仍然存在的问题是,如果你调用POST或GET进行搜索。我已经尝试了field,现在它给了我这个错误:处理器'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor'(模板:“讲师搜索”-第35行,第48列)执行过程中出现错误。正如我在回答中所写,你还没有更改整个表单。这个领域必须是主题不是勒克特雷萨奇对不起,你是对的,我是瞎子。。。没有将美元符号
$
替换为星号
*
,谢谢!