一、环境及软件
环境:
JDK 1.8.0
maven项目
MySQL 5.7
软件:
IDEA 2022
Postman (接口测试)
二、使用IDEA搭建springboot项目
1.新建spring项目
服务器url修改为阿里的:https://start.aliyun.com
2.选择springboot版本和依赖项
3.当前项目com.example.portal_V1目录下为源码目录,该目录下新建以下文件夹
4.application.properties配置
修改为你自己的数据库信息
# 应用名称
spring.application.name=portal_V1
# 应用服务 WEB 访问端口
server.port=8080
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/temp?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=
5.SQL文件
在你的数据库中新建一张user表
字段名 类型 注释 id bigint 主键 username varchar 用户名 password varchar 密码
/*
Navicat Premium Data Transfer
Source Server : 1
Source Server Type : MySQL
Source Server Version : 100417
Source Host : localhost:3306
Source Schema : temp
Target Server Type : MySQL
Target Server Version : 100417
File Encoding : 65001
Date: 12/11/2022 16:25:14
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名',
`password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '密码',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户信息' ROW_FORMAT = DYNAMIC;
SET FOREIGN_KEY_CHECKS = 1;
6.PortalV1Application.java文件修改
@MapperScan("com.example.portal_v1.mapper") //设置mapper文件扫描路径
@SpringBootApplication @MapperScan("com.example.portal_v1.mapper") public class PortalV1Application { public static void main(String[] args) { SpringApplication.run(PortalV1Application.class, args); } }
7.Utils目录下新建ResultUtil.java
统一响应封装类
package com.example.portal_v1.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResultUtil<T> {
private int status;
private String message;
private String time =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
private T data;
private Boolean success;
public void success(int status,String message){
this.status = status;
this.message=message;
this.success=true;
}
public void success(int status,String message,T data){
this.status = status;
this.message=message;
this.success=true;
this.data=data;
}
public void error(int status,String message, HttpServletResponse response){
this.status = status;
this.message=message;
this.success=false;
response.setStatus(status);
response.setHeader("Content-Type","application/json;charset=utf8");
}
public void error(int status,String message){
this.status = status;
this.message=message;
this.success=false;
}
public void dataValidation422(String message, HttpServletResponse response){
this.status = 422;
this.message=message;
this.success=false;
response.setStatus(422);
response.setHeader("Content-Type","application/json;charset=utf8");
}
public void noAuthorization401( HttpServletResponse response){
this.status = 401;
this.message="未登录/未授权";
this.success=false;
response.setStatus(401);
response.setHeader("Content-Type","application/json;charset=utf8");
}
}
8.model目录下文件
UserModel.java
user表映射实体类
package com.example.portal_v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserModel {
private int id;
private String username;
private String password;
}
9.model目录下新建Vo目录,Vo目录下新建LoginVo.java
package com.example.portal_v1.model.Vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LoginVo {
@NotBlank(message = "用户名不能为空")
private String username;
@NotBlank(message = "密码不能为空")
private String password;
}
10.mapper目录下新建AuthMapper.java文件
package com.example.portal_v1.mapper;
import com.example.portal_v1.model.UserModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface AuthMapper {
@Select("SELECT * FROM `user` WHERE `username` = #{username}")
UserModel getUserByUsername(String username);
}
11.controller目录文件
AuthController.java
用户身份相关接口
package com.example.portal_v1.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.portal_v1.Utils.ResultUtil;
import com.example.portal_v1.mapper.AuthMapper;
import com.example.portal_v1.model.UserModel;
import com.example.portal_v1.model.Vo.LoginVo;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
@RestController
public class AuthController {
@Resource
AuthMapper authMapper;
@RequestMapping("login")
public Object login(@RequestBody @Valid LoginVo loginVo, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
ResultUtil resultUtil = new ResultUtil();
if(bindingResult.hasErrors()){
resultUtil.dataValidation422(bindingResult.getFieldError().getDefaultMessage(),response);
return resultUtil;
}
UserModel userInfo = authMapper.getUserByUsername(loginVo.getUsername());
if(userInfo!=null){
if(userInfo.getPassword().equals(loginVo.getPassword())){
userInfo.setPassword(null);
resultUtil.success(200,"登录成功",userInfo);
}else{
resultUtil.success(400,"登录失败,密码错误");
}
}else{
resultUtil.success(404,"登录失败,用户不存在");
}
return resultUtil;
}
}