pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.itheimagroupId>
<artifactId>reggie_take_outartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.4.5version>
<relativePath/>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<scope>compilescope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.2version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.20version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.76version>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.23version>
dependency>
dependencies>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>11maven.compiler.source>
<maven.compiler.target>11maven.compiler.target>
properties>
project>
注意:使用boot框架的需要手动修改MySQL的版本
application.yml配置文件
server:
port: 8080
spring:
application:
name: reggie_take_out
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: "20020630"
mybatis-plus:
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
导入完成之后进行静态资源映射(如果是直接使用springboot框架就不需要进行静态资源映射)
创建一个配置类继承 WebMvcConfigurationSupport
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开启进行静态资源映射");
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
}
}
//员工实体类
@Data
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String name;
private String password;
private String phone;
private String sex;
private String idNumber;//身份证
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
}
创建 一个返回结果类(前后端协议)
//通用的返回结果类
//服务端响应的数据最终都会封装成此对象
@Data
public class R<T> {
private Integer code; //编码:1成功,0和其它数字为失败
private String msg; //错误信息
private T data; //数据
private Map map = new HashMap(); //动态数据
//登录成功
public static <T> R <T> success(T object) {
R<T> r = new R<T>();
r.data = object;
r.code = 1;
return r;
}
public static <T> R<T> error(String msg) {
R r = new R();
r.msg = msg;
r.code = 0;
return r;
}
public R<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
}
创建一个接口(EmployeeMapper)继承BaseMapper
创建一个接口(EmployeeService)继承IService
继承ServiceImpl
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
//员工登录
@PostMapping("/login")
public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
//将页面提交的密码进行MD5加密处理
String password = employee.getPassword();
password=DigestUtils.md5DigestAsHex(password.getBytes());
//根据用户名查询数据库
LambdaQueryWrapper<Employee> lambdaQueryWrapper=new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(Employee::getUsername,employee.getUsername());
//用户名设置了唯一约束
Employee emp = employeeService.getOne(lambdaQueryWrapper);
//判断用户名是否存在
if (emp==null){
return R.error("登录失败");
}
//密码比对
if (!emp.getPassword().equals(password)){
return R.error("登录失败");
}
//查看账号状态是否被禁用
if (emp.getStatus()==0){
return R.error("账号已禁用");
}
//登录成功,将用户的id存入Session中
HttpSession session = request.getSession();
session.setAttribute("employee",emp.getId());
return R.success(emp);
}
}
//用户退出
@PostMapping("/logout")
R<String> logOut(HttpServletRequest request){
//清除数据
request.getSession().removeAttribute("employee");
return R.success("退出成功");
}
添加拦截器(当用户没有登录不能进入首页)
@Slf4j
//检查用户是否完成登录
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//路径匹配器,支持通配符
private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpServletResponse response=(HttpServletResponse) servletResponse;
//定义不需要处理的请求路径
String []urls=new String[]{
"/employee/login",
"employee/logout",
"/backend/**",
"/front/**"
};
//获取本次请求的uri
String requestURI = request.getRequestURI();
//判断此次请求是否需要处理
log.info("拦截到路径"+requestURI);
boolean check = check(urls, requestURI);
if (check){
//放行
filterChain.doFilter(request, response);
return;
}
//检查登录状态
if (request.getSession().getAttribute("employee")!=null){
//已经登录
//放行
filterChain.doFilter(request, response);
return ;
}
//未登录
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));//request.js9
return ;
}
//判断请求是否需要处理的方法
public boolean check(String[] urls,String requestURI) {
for (String url : urls) {
boolean match = PATH_MATCHER.match(url, requestURI);
if (match) {
return true;
}
}
return false;
}
}
注意:要想
@WebFilter
注解生效,需要在配置类上标注另外一个注解@ServletComponentScan
用于扫描使其生效