【发布时间】:2017-05-09 22:38:20
【问题描述】:
我想通过 CrudRepository 的方法创建一个简单的搜索按钮,并在网站上显示记录。 我是初学者,所以对你来说可能看起来太琐碎了,但我还是在征求意见:)
StudentRepository.java
public interface StudentRepository extends CrudRepository<Student, Integer> {
Iterable<Student> findBySurname(String surname);
}
StudentService.java
public interface StudentService {
Iterable<Student> listStudentsBySurname(String surname);
}
StudentServiceImpl.java
@Service
public class StudentServiceImpl implements StudentService {
private StudentRepository studentRepository;
@Autowired
public void setStudentRepository(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@Override
public Iterable<Student> listStudentsBySurname(String surname) {
return studentRepository.findBySurname(surname);
}
}
students.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title></title>
<!--/*/ <th:block th:include="fragments/headerincStudent :: head"></th:block> /*/-->
</head>
<body>
<div class="container">
<!--/*/ <th:block th:include="fragments/headerStudent :: header"></th:block> /*/-->
<h2>Search for students</h2>
<form th:object="${student}" th:action="@{/students}" method="get">
<input type="text" name="search" id="search" th:value="${search}"/>
<input type="submit" value="Search"/>
<div th:if="${not #lists.isEmpty(search)}">
<h2>Students List</h2>
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Name</th>
<th>Surname</th>
</tr>
<tr th:each="student: ${search}">
<td th:text="${student.idStudent}"><a href="/student/${student.idStudent}">idStudent</a></td>
<td th:text="${student.name}">name</td>
<td th:text="${student.surname}">surname</td>
</tr>
</table>
</div>
</form>
</div>
</body>
</html>
StudentController.java
@Controller
public class StudentController {
private StudentService studentService;
@Autowired
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
@RequestMapping(value = "students/{surname}", method = RequestMethod.GET)
public String showStudentBySurname(@PathVariable String surname, Model model) {
model.addAttribute("search", studentService.listStudentsBySurname(surname));
return "students";
}
}
我设法用我的本地数据库做简单的 CRUD。我已经直接在网站上通过 findAll 方法查看了学生列表,但现在我想对带有按钮的文本字段执行此操作,但我不知道接下来要做什么。
【问题讨论】:
标签: java spring hibernate thymeleaf crud