文章目錄
- 介紹
- 代碼拆分
- Dao層
- server層
- controller層
- 運行結果
介紹
在我們進行程序設計以及程序開發時,盡可能讓每一個接口、類、方法的職責更單一些(單一職責原則)。
單一職責原則:一個類或一個方法,就只做一件事情,只管一塊功能。這樣就可以讓類、接口、方法的復雜度更低,可讀性更強,擴展性更好,也更利于后期的維護。
從組成上看可以分為三個部分:
- 數據訪問:負責業務數據的維護操作,包括增、刪、改、查等操作。
- 邏輯處理:負責業務邏輯處理的代碼。
- 請求處理、響應數據:負責,接收頁面的請求,給頁面響應數據。
按照上述的三個組成部分,在我們項目開發中呢,可以將代碼分為三層:
- Controller:控制層。接收前端發送的請求,對請求進行處理,并響應數據。
- Service:業務邏輯層。處理具體的業務邏輯。
- Dao:數據訪問層(Data Access Object),也稱為持久層。負責數據訪問操作,包括數據的增、刪、改、查。
三層架構的程序執行流程:
- 前端發起的請求,由Controller層接收(Controller響應數據給前端)
- Controller層調用Service層來進行邏輯處理(Service層處理完后,把處理結果返回給Controller層)
- Serivce層調用Dao層(邏輯處理過程中需要用到的一些數據要從Dao層獲取)
- Dao層操作文件中的數據(Dao拿到的數據會返回給Service層)
代碼拆分
Dao層
創建UserDao接口
package com.example.Dao;import java.util.List;public interface UserDao {/*** 加載用戶數據* @return*/public List<String> findAll();
}
創建UserDaoImpl接口,實現文件操作
package com.example.Dao.impl;import cn.hutool.core.io.IoUtil;
import com.example.Dao.UserDao;import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;public class UserDaoImpl implements UserDao {@Overridepublic List<String> findAll() {//加載并讀取user.txtInputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());return lines;}
}
server層
創建UserSerivce接口
package com.example.service;import com.example.pojo.User;import java.util.List;public interface UserService {/*** 查詢所有用戶信息* @return*/public List<User> findAll();
}
創建UserSerivceImpl接口,實現數據操作,返回對象
package com.example.service.impl;import com.example.Dao.UserDao;
import com.example.Dao.impl.UserDaoImpl;
import com.example.pojo.User;
import com.example.service.UserService;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;public class UserServiceImpl implements UserService {private UserDao userDao = new UserDaoImpl();@Overridepublic List<User> findAll() {//調用Dao獲取數據List<String> lines = userDao.findAll();//解析用戶信息,封裝List<User> userList = lines.stream().map(line -> {String[] parts = line.split(",");Integer id = Integer.parseInt(parts[0]);String username = parts[1];String password = parts[2];String name = parts[3];Integer age = Integer.parseInt(parts[4]);LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));return new User(id, username, password, name, age, updateTime);}).toList();//返回return userList;}
}
controller層
創建UserController類
@RestController
public class UserController {private UserService userService = new UserServiceImpl();@RequestMapping("/list")public List<User> list() throws Exception{List<User> userList = userService.findAll();//返回json數據return userList;}
}
運行結果
目錄
運行并訪問