文件结构随便贴一贴,跟着狂神的B站“SpringBoot”视频做的项目,期间许多细节问题,终究是学艺不精。
- pojo层定义对象的基本属性
- service层定义并实现各种方法(函数)
- dao层(xxxMapper.java)提供"方法->SQL"的接口
- mapper目录下xxxMapper.xml是各种方法的SQL实现
- controller层负责
- 接收前端 请求/请求+数据
- 调用service方法处理
- 处理完成后给前端返回结果
个人理解:dao层的接口和SQL实现使得我们的数据能够保存在数据库中&从数据库中读取数据
pom.xml二话不说先导依赖
配置文件 application.properties4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.6 com web01 0.0.1-SNAPSHOT web01 web01 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-jdbc org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1 org.springframework.boot spring-boot-starter-web org.projectlombok lombok true mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
#我们的配置文件的真实位置 spring.messages.basename=i18n.login spring.thymeleaf.cache=false #时间日期格式化 spring.mvc.format.date=yyyy-MM-dd #整合数据库 spring.datasource.username=root spring.datasource.password=095810 #添加时区信息以及编码信息 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #mybatis mybatis.type-aliases-package=com.pojo mybatis.mapper-locations=classpath:mybatis/mapper/*.xml测试类
Web01ApplicationTests测试数据库是否连接成功,成功了再继续,当然要用到数据库还得先完成底层代码并写好接口等等
package com;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class Web01ApplicationTests {
//DI注入数据源
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
//看一下默认数据源
System.out.println(dataSource.getClass());
//获得连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//关闭连接
connection.close();
}
}
pojo层
Department.java
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
Employee.java
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
//员工表
@Data
//@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Department department;
private Date birth;
public Employee(Integer id, String lastName ,String email,Integer gender, Department department){
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
this.birth = new Date();
}
}
service层
DepartmentService.java
package com.service;
import com.dao.DepartmentMapper;
import com.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
@Service
public class DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;//报红不用管
//获取所有部门
public Collection getDepartments(){
return departmentMapper.getDepartments();
}
//通过ID获取部门
public Department getDepartmentById(Integer id){
return departmentMapper.getDepartmentById(id);
}
}
EmployeeService.java
package com.service;
import com.dao.EmployeeMapper;
import com.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper; //报红不用管
//增加一位员工
public void save(Employee employee){
employeeMapper.save(employee);
}
//更新员工信息
public void update(Employee employee){
employeeMapper.update(employee);
}
//查询全部员工
public Collection getAll(){
return employeeMapper.getAll();
}
//通过ID查询员工
public Employee getEmployeeById(Integer id){
return employeeMapper.getEmployeeById(id);
}
//通过ID删除一位员工
public void deleteEmployeeById(Integer id){
employeeMapper.deleteEmployeeById(id);
}
}
dao层
DepartmentMapper.java两类mapper一起食用
package com.dao;
import com.pojo.Department;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
public interface DepartmentMapper {
// 获取所有部门信息
List getDepartments();
// 通过id获得部门
Department getDepartmentById(Integer id);
}
EmployeeMapper.java
package com.dao;
import com.pojo.Employee;
import org.apache.ibatis.annotations.Mapper;
import java.util.Collection;
@Mapper
public interface EmployeeMapper {
//增加一位员工
void save(Employee employee);
//更新员工信息
void update(Employee employee);
//查询全部员工
Collection getAll();
//通过ID查询员工
Employee getEmployeeById(Integer id);
//通过ID删除一位员工
void deleteEmployeeById(Integer id);
}
DepartmentMapper.xml
EmployeeMapper.xml
controller层 DepartmentController.javalastname,email,gender,departmentId,birth SELECT * FROM employee,department WHERe employee.departmentId=department.id INSERT INTO employee #{lastName},#{email},#{gender},#{department.id},#{birth} UPDATE employee lastname = #{lastName}, email = #{email}, gender = #{gender}, departmentId = #{department.id}, birth = #{birth}, id=#{id} SELECT * FROM employee WHERe id=#{id} DELETE FROM employee WHERe id=#{id}
package com.controller;
import com.dao.DepartmentMapper;
import com.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class DepartmentController {
@Autowired
DepartmentMapper departmentMapper;
// 查询全部部门
@GetMapping("/getDepartments")
public List getDepartments(){
return departmentMapper.getDepartments();
}
// 查询全部部门
@GetMapping("/getDepartment/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDepartmentById(id);
}
}
EmployeeController.java
package com.controller;
import com.dao.DepartmentMapper;
import com.pojo.Department;
import com.pojo.Employee;
import com.service.DepartmentService;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.Collection;
@Controller
public class EmployeeController {
@Autowired
private DepartmentService departmentService;
@Autowired
private EmployeeService employeeService;
@RequestMapping("/emps")
public String list(Model model){
Collection employees = employeeService.getAll();
model.addAttribute("emps",employees);
return "emp/list";
}
@GetMapping("/emp")
public String toAddpage(Model model){
//查出所有部门
Collection departments = departmentService.getDepartments();
model.addAttribute("departments",departments);
return "emp/add";
}
@PostMapping("/emp")
public String Add(Employee employee){
//添加操作
System.out.println("save====>"+employee.toString());
employeeService.save(employee);
return "redirect:/emps";
}
@GetMapping("/emp/{id}")
public String toUpdate(@PathVariable("id") Integer id,Model model){
//查出原来的数据
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("emp",employee);
//查出所有部门
Collection departments = departmentService.getDepartments();
System.out.println(departments.toString());
model.addAttribute("departments",departments);
return "emp/update";
}
@PostMapping("/emp/updateEmp")
public String Update(Employee employee){
employeeService.update(employee);
return "redirect:/emps";
}
@RequestMapping("/delete/{id}")
public String Delete(@PathVariable("id") Integer id){
employeeService.deleteEmployeeById(id);
return "redirect:/emps";
}
@RequestMapping("/out")
public String loginOut(HttpSession session){
session.removeAttribute("loginUser");
return "redirect:/";
}
}
LoginController.java
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(
@RequestParam ("username") String username,
@RequestParam ("password") String password,
Model model, HttpSession session){
//具体业务
//登录名非空且密码为“123456”即可
if (!StringUtils.isEmpty(username) && "123456".equals(password)){
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else {
//登陆失败
model.addAttribute("msg","用户名或者密码错误");
return "index";
}
}
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.invalidate();
return "redirect:/index.html";
}
}
config
LoginHandlerInterceptor.java该目录下基本是前端的东西
package com.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser == null){
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}
MylocaleResolver.java
package com.config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
//国际化配置
public class MylocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String langue = request.getParameter("l");
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(langue)){
//字符串分割方法
String[] split = langue.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
MymvcConfig.java
package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MymvcConfig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("index.html").setViewName("index");
registry.addViewController("main.html").setViewName("dashboard");
}
@Bean
//在配置文件中注册自己的重写组件
public LocaleResolver localeResolver(){
return new MylocaleResolver();
}
//为测试方便可暂时关闭拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
//拦截路径
.addPathPatterns("/**")
//排除以下路径
.excludePathPatterns("/index.html","/","/user/login","/css/*","/img/*","/js/*");
}
}
静态资源部分
略
链接:https://pan.baidu.com/s/18ECtCSXJcAA__MhLYAxyGQ
提取码:sy68
用户:登录+注销
员工:增删改+List (未添加查找功能)



