学习springboot之课程表显示
在本次课程结束后,汪老师给我们布置了一个作业如下:
使用thymeleaf和bootstrap显示课程信息表(内容自定)的页面。
那么就让我们快速解决这个问题吧!在学习了springboot后我发现其实掌握了springboot的核心配置后,要写的代码便会减少很多啦,很多时候可以使用注解,在今天的作业中我们也会看到。
ps:注意一下内容不完成,不要复制粘贴!!!
一、项目结构
二、建立实体类
在com.itheima下建立一个unity包,在包下建立课程信息类。这里用了很多注解就减少了代码的写入量
public class Course {
private Integer id;
private String name;
private double credit;
private Integer hour;
private String type;
}
三、yaml配置
server:
port: 80
spring:
thymeleaf:
cache: false
四、pom.xml文件
其中导入你需要的依赖,不止这些
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
五、建立控制类
这里还是使用thymeleaf模板将对象实例化,内容自写。(不完整实例如下)
@Controller
public class courseController {
@GetMapping("/index")
public String index(Model model){
Course c1=new Course(1,"高等数学(1)",3.0,36,"必修课");
Course c2=new Course(2,"高等数学(2)",3.0,36,"必修课");
List<Course> list=new ArrayList();
list.add(c1);
list.add(c2);
model.addAttribute("Courses",list);
return "show";
}
}
六、建立我们需要渲染的网页show.html
里面含有大量thymeleaf和html语法,不熟悉的同学可以自行重新学习。记得自行建立bootstrap的css和js。
<title>首页</title>
<link th:href ="@{http://localhost/css/bootstrap.css}" rel="stylesheet">
<link th:href ="@{http://localhost/js/bootstrap.js}" rel="stylesheet">
</head>
<body>
<div class="container">
<table class="table">
<thead>
<th>课程编号</th>
<th>课程名字</th>
<th>学分</th>
<th>学时</th>
<th>类型</th>
</thead>
<tbody>
<tr th:each="Cou:${Courses}">
<td th:text="${Cou.id}"></td>
<td th:text="${Cou.name}"></td>
<td th:text="${Cou.credit}"></td>
<td th:text="${Cou.hour}"></td>
<td th:text="${Cou.type}"></td>
</tr>
</tbody>
</table>
</div>
七、网页显示
这样我们就可以得到老师所要求的页面啦。
八、总结
上述步骤讲的不够自行,笔者也是希望大家可以自己慢慢了解其中原理。那么其中的一些细节就请大家自行解决了。同时也请多多指教,指出不足,一起交流学习进步。