一、整合JPA
1、添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2、创建数据库(mydb2019)和表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for ay_user
-- ----------------------------
DROP TABLE IF EXISTS `ay_user`;
CREATE TABLE `ay_user` (
`id` int(11) NOT NULL,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of ay_user
-- ----------------------------
INSERT INTO `ay_user` VALUES (1, 'libai', '123456');
-- ----------------------------
-- Table structure for checking_in
-- ----------------------------
DROP TABLE IF EXISTS `checking_in`;
CREATE TABLE `checking_in` (
`id` int(11) NOT NULL,
`employee_id` int(11) NULL DEFAULT NULL,
`employee_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`work_day` int(11) NULL DEFAULT NULL,
`month_rest_day` int(11) NULL DEFAULT NULL,
`leave_day` int(11) NULL DEFAULT NULL,
`late_min` int(11) NULL DEFAULT NULL,
`fine_money` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for phone_type
-- ----------------------------
DROP TABLE IF EXISTS `phone_type`;
CREATE TABLE `phone_type` (
`type_id` int(11) NOT NULL AUTO_INCREMENT,
`number_part` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`type_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`type_remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`type_id`) USING BTREE,
INDEX `type_id`(`type_id`, `type_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of phone_type
-- ----------------------------
INSERT INTO `phone_type` VALUES (1, '15100000000', '中国联通', '10010');
INSERT INTO `phone_type` VALUES (3, '111111111', '中国移动', 'test');
SET FOREIGN_KEY_CHECKS = 1;
3、修改数据库连接等配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydb2019?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.name=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4、新建model/AyUser 实体类
@Entity
@Table(name="ay_user")
public class AyUser {
@Id //声明主键
@GeneratedValue(strategy=GenerationType.IDENTITY) //主键策略
private String id;
private String name;
private String password;
//省略get/set方法
}
5、新建AyUserRepository
public interface AyUserRepository extends JpaRepository<AyUser,String> {
}
6、AyUserService
public interface AyUserService {
AyUser findbyId(String id);
List<AyUser> findAll();
AyUser save(AyUser ayUser);
void delete(String id);
}
7、AyUserServiceImpl
@Service
public class AyUserServiceImpl implements AyUserService {
@Resource
private AyUserRepository ayUserRepository;
@Override
public AyUser findbyId(String id) {
return ayUserRepository.findById(id).orElse(null);
}
@Override
public List<AyUser> findAll() {
return ayUserRepository.findAll();
}
@Override
public AyUser save(AyUser ayUser) {
return ayUserRepository.save(ayUser);
}
@Override
public void delete(String id) {
ayUserRepository.deleteById(id);
}
}
8、HelloController
@RestController
public class HelloController {
@Autowired
AyUserService myService;
@RequestMapping("/hello")
public String First() {
return myService.findAll().get(0).getName();
}
}
9、测试
二、整合thymeleaf
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、修改配置文件
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
3、index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
</head>
<body>
<table border="1" cellspacing="0">
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
<tr th:each="user:${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
</body>
</html>
4、AyUserController
@Controller
public class AyUserController {
@Resource
private AyUserService ayUserService;
@RequestMapping("/showusers")
public String showusers( Model model) {
List<AyUser> ayUser=ayUserService.findAll();
model.addAttribute("users",ayUser);
return "index";
}
}
5、测试
三、开启事务
在ServiceImpl 方法或者类上添加 @Transactional
注解即可。
四、Filter过滤器 和 Listener监听器
1、过滤器
过滤器和拦截器在功能方面很类似,但是在具体技术实现方面,差距还是比较大的。在面向对象编程的过程中,我们很容易通过继承、多态来解决纵向扩展。 但是对于横向的功能,比如,在所有的service方法中开启事务,或者统一记录日志等功能,面向对象的是无法解决的。所以AOP——面向切面编程其实是面向对象编程思想的一个补充。而过滤器和拦截器都属于面向切面编程的具体实现。而两者的主要区别包括以下几个方面:
1、Filter是依赖于Servlet容器,属于Servlet规范的一部分,而拦截器则是独立存在的,可以在任何情况下使用。
2、Filter的执行由Servlet容器回调完成,而拦截器通常通过动态代理的方式来执行。
3、Filter的生命周期由Servlet容器管理,而拦截器则可以通过IoC容器来管理,因此可以通过注入等方式来获取其他Bean的实例,因此使用会更方便。
2、新建UrlFilter 类
当访问/success/info时,正常访问;访问/success/ 下的其他页面时,会跳转到/failed 页面。
@WebFilter(filterName = "test", urlPatterns = "/success/*")
public class UrlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("----------------------->过滤器被创建");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
String requestURI = req.getRequestURI();
System.out.println("--------------------->过滤器:请求地址"+requestURI);
if(!requestURI.contains("info")){
servletRequest.getRequestDispatcher("/failed").forward(servletRequest, servletResponse);
}else{
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
System.out.println("----------------------->过滤器被销毁");
}
}
3、HelloController
添加/failed 和/success/info 两个接口
@RestController
public class HelloController {
@Autowired
AyUserService myService;
@RequestMapping("/hello")
public String First() {
return myService.findAll().get(0).getName();
}
@RequestMapping("/failed")
public Map<String, String> requestFailed(){
Map<String, String> map = new HashMap<>();
map.put("code", "-1");
map.put("msg", "请求错误");
return map;
}
@RequestMapping("/success/info")
public AyUser userInfo(){
AyUser user = new AyUser();
user.setName("xiaodong");
user.setPassword("123456");
user.setId("2020");
return user;
}
}
4、在启动类添加注解
@ServletComponentScan
5、测试
6、监听器
监听器也叫Listener,是servlet的监听器,可以用于监听Web应用中某些对象,信息的创建,销毁,增加,修改,删除等动作的发生,然后做出相应的响应处理。当范围对象的状态发生变化时,服务器自动调用监听器对象中的方法,常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等。
7、新建RequestListener 类
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
System.out.println("---------------------------->请求Listener销毁");
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
System.out.println("---------------------------->请求Listener创建");
}
}
7、测试
当访问页面时,控制台打印:
五、增删改查小案例
1、PhoneType
@Entity
@Table(name = "phone_type")
public class PhoneType {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private String type_id;
private String number_part;
private String type_name;
private String type_remark;
public String getType_id() {
return type_id;
}
public void setType_id(String type_id) {
this.type_id = type_id;
}
public String getNumber_part() {
return number_part;
}
public void setNumber_part(String number_part) {
this.number_part = number_part;
}
public String getType_name() {
return type_name;
}
public void setType_name(String type_name) {
this.type_name = type_name;
}
public String getType_remark() {
return type_remark;
}
public void setType_remark(String type_remark) {
this.type_remark = type_remark;
}
}
2、PhoneTypeRepository
public interface PhoneTypeRepository extends JpaRepository<PhoneType,String> {
}
3、PhoneTypeService
public interface PhoneTypeService {
PhoneType findById(String id);
List<PhoneType> findAll();
PhoneType save(PhoneType phoneType);
void delete(String id);
}
4、PhoneTypeServiceImpl
@Service
public class PhoneTypeServiceImpl implements PhoneTypeService {
@Resource
private PhoneTypeRepository phoneTypeRepository;
@Override
public PhoneType findById(String id) {
return phoneTypeRepository.findById(id).orElse(null);
}
@Override
public List<PhoneType> findAll() {
return phoneTypeRepository.findAll();
}
@Override
public PhoneType save(PhoneType phoneType) {
return phoneTypeRepository.save(phoneType);
}
@Override
public void delete(String id) {
phoneTypeRepository.deleteById(id);
}
}
5、PhoneTypeController
@Controller
public class PhoneTypeController {
@Autowired
PhoneTypeService phoneTypeService;
String uid;
@RequestMapping("/phone")
public String phone_type(Model model){
List<PhoneType> phoneTypes = phoneTypeService.findAll();
model.addAttribute("phones",phoneTypes);
return "phone_type.html";
}
//跳转去添加页面
@GetMapping("/add")
public String toAdd(Model model){
return "phoneType/add.html";
}
//添加操作
@PostMapping("/add")
public String addPT(PhoneType phoneType){
//保存信息
phoneTypeService.save(phoneType);
//重定向到列表页面
return "redirect:/phone";
}
//跳转到更新页面
@GetMapping("/toUpdate/{id}")
public String toUpdate(@PathVariable("id") String id, Model model){
//根据id查出来的信息
PhoneType phoneType = phoneTypeService.findById(id);
uid = id;
//将信息返回给页面
model.addAttribute("phones",phoneType);
return "phoneType/update.html";
}
//更新操作
@PostMapping("/update")
public String updatePT(PhoneType phoneType){
//根据id查出来的信息
PhoneType py = phoneTypeService.findById(uid);
py.setType_name(phoneType.getType_name());
py.setNumber_part(phoneType.getNumber_part());
py.setType_remark(phoneType.getType_remark());
phoneTypeService.save(py);
return "redirect:/phone";
}
//删除操作
@GetMapping("/delPhone/{id}")
public String delPhone(@PathVariable("id") String id){
phoneTypeService.delete(id);
return "redirect:/phone";
}
}
6、列表页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>手机号类型</title>
</head>
<style type="text/css">
button{
padding: 5px 20px 5px 20px;
background-color: #8488f0;
color: white;
}
</style>
<body>
<div>
<!--<input type="text"><button>点我查询</button>-->
<a th:href="@{/add}"><button>添加</button></a>
</div>
<table border="1" cellspacing="0">
<thead>
<tr>
<th>编号</th>
<th>手机号码</th>
<th>运营商类型</th>
<th>备注</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="phone:${phones}">
<td th:text="${phone.type_id}"></td>
<td th:text="${phone.number_part}"></td>
<td th:text="${phone.type_name}"></td>
<td th:text="${phone.type_remark}"></td>
<td >
<a class="btn btn-sm btn-primary" th:href="@{/toUpdate/}+${phone.type_id}">编辑</a>
<a class="btn btn-sm btn-danger" th:href="@{/delPhone/}+${phone.type_id}">删除</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
7、添加页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加</title>
</head>
<body>
<h2>添加信息</h2>
<form th:action="@{/add}" method="post">
<table>
<tr>
<td><label for="InputNum">手机号</label></td>
<td><input name="number_part" type="text" required id="InputNum" placeholder="手机号"></td>
</tr>
<tr>
<td><label for="InputName">运营商</label></td>
<td> <input name="type_name" type="text" required id="InputName" placeholder="运营商类型" ></td>
</tr>
<tr>
<td><label for="InputText">备注</label></td>
<td> <input name="type_remark" type="text" required id="InputText" placeholder="备注" ></td>
</tr>
<tr>
<td> <button type="submit" >提交</button></td>
</tr>
</table>
</form>
</body>
</html>
8、更新页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>更新</title>
</head>
<body>
<h2>更新操作</h2>
<form th:action="@{/update}" th:method="post">
<table>
<tr>
<td><label>手机号</label></td>
<td><input name="number_part" type="text" th:value="${phones.number_part}"></td>
</tr>
<tr>
<td><label>运营商</label></td>
<td><input name="type_name" type="text" th:value="${phones.type_name}"></td>
</tr>
<tr>
<td><label>备注</label></td>
<td><input name="type_remark" type="text" th:value="${phones.type_remark}"></td>
</tr>
<tr>
<td> <button type="submit" >提交</button></td>
</tr>
</table>
</form>
</body>
</html>
9、效果
添加
更新
删除编号18的