要求:创建基于Maven的SpringBoot项目;创建基于Thymeleaf的HTML模板文件,作为程序主页;创建Controller类,响应客户端请求;添加显示和删除学生信息的功能;
SpringMVC以Contrller响应客户端的请求; SpringMVC以Thymeleaf添代了JSP;删除一个学生:取得学生的sid,服务端跟据sid来构建删除SQL语句。
具体的操作步骤及每个步骤后的显示图是怎样的?
student,包含字段id,name,age,address。
步骤1: 创建基于Maven的SpringBoot项目
在提示窗口中选择“Open as Project”来打开创建好的项目。
步骤2: 创建基于Thymeleaf的HTML模板文件,作为程序主页
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>学生信息管理系统</title>
</head>
<body>
<h1>学生信息管理系统</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>地址</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="student : ${students}">
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.age}"></td>
<td th:text="${student.address}"></td>
<td>
<a th:href="@{'/delete/' + ${student.id}}">删除</a>
</td>
</tr>
</tbody>
</table>
<br>
<form method="POST" action="/add">
<label>ID:</label><input type="text" name="id"/>
<label>姓名:</label><input type="text" name="name"/>
<label>年龄:</label><input type="text" name="age"/>
<label>地址:</label><input type="text" name="address"/>
<input type="submit" value="添加"/>
</form>
</body>
</html>
此示例演示了如何使用Thymeleaf模板引擎,从服务器端获取学生信息并在页面上以表格的形式显示,同时在每个学生条目的操作栏中添加了“删除”链接。
步骤3: 创建Controller类,响应客户端请求
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/")
public String index(Model model) {
List<Student> students = studentService.getAllStudents();
model.addAttribute("students", students);
return "index";
}
@PostMapping("/add")
public String addStudent(HttpServletRequest request) {
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
String address = request.getParameter("address");
Student student = new Student(id, name, age, address);
studentService.addStudent(student);
return "redirect:/";
}
@GetMapping("/delete/{id}")
public String deleteStudent(@PathVariable String id) {
studentService.deleteStudent(id);
return "redirect:/";
}
}
此示例演示了如何使用Spring MVC框架创建一个简单的Controller类,用来响应客户端的请求并返回相应的视图,其中包括主页(即步骤2创建的index.html页面)和添加、删除学生的方法。
步骤4: 添加显示和删除学生信息的功能