一、创建spingboot项目框架
1.首先创建一个空的项目作为父项目,之后的所有都在此基础上创建模块进行开发。
2.创建负责登录注册功能模块
二、启动项目
1.出现如下错误,代表着端口号被占用,这个时候,我们可以进行端口号的修改。
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2024-08-29 13:35:55.964 ERROR 27624 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
//这行错误提示我们8080端口被占用
Web server failed to start. Port 8080 was already in use.
Action:
Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
Process finished with exit code 1
2.修改login模块的端口号,在配置文件application.properties中进行修改,端口号设置为9090
//将服务端口设置为9090,这个端口号可以自己设置
server.port=9090
3.再次启动项目,出现如下提示,代表着项目启动完成
//自己项目的启动日志 :MySpringBootLoginApplication 应用正在使用 Java 17.0.10 版本在 WIN-20240219KIE 机器上启动,进程ID为 21296,工作目录在 E:\AnZhuangChengXu\java Project\spring01\mySpringBoot
2024-08-29 13:39:16.960 INFO 21296 --- [ main] c.l.m.MySpringBootLoginApplication : Starting MySpringBootLoginApplication using Java 17.0.10 on WIN-20240219KIE with PID 21296 (E:\AnZhuangChengXu\java Project\spring01\mySpringBoot\mySpringBoot-login\target\classes started by Administrator in E:\AnZhuangChengXu\java Project\spring01\mySpringBoot)
//没有设置活动的配置文件,将使用默认的 "default" 配置文件
2024-08-29 13:39:16.962 INFO 21296 --- [ main] c.l.m.MySpringBootLoginApplication : No active profile set, falling back to 1 default profile: "default"
//tomcat初始化启动,Tomcat 服务器已初始化,HTTP服务端口为 9090
2024-08-29 13:39:17.677 INFO 21296 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9090 (http)
//ervlet 引擎(Apache Tomcat/9.0.68)正在启动
2024-08-29 13:39:17.685 INFO 21296 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2024-08-29 13:39:17.685 INFO 21296 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68]
//Spring 嵌入式 Web 应用上下文正在初始化,初始化完成耗时 746 毫秒
2024-08-29 13:39:17.765 INFO 21296 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2024-08-29 13:39:17.765 INFO 21296 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 746 ms
//MySpringBootLoginApplication 应用已启动,启动耗时 1.408 秒,JVM 运行时间为 2.349 秒
2024-08-29 13:39:18.038 INFO 21296 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path ''
2024-08-29 13:39:18.045 INFO 21296 --- [ main] c.l.m.MySpringBootLoginApplication : Started MySpringBootLoginApplication in 1.408 seconds (JVM running for 2.349)
//Spring 的 DispatcherServlet 正在初始化,初始化完成耗时 0 毫秒
2024-08-29 13:39:42.548 INFO 21296 --- [nio-9090-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-08-29 13:39:42.549 INFO 21296 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2024-08-29 13:39:42.549 INFO 21296 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
三、创建后端统一返回结果类型
引用:构建spring boot web项目:三、设置统一返回、统一异常处理_springboot 编写统一返回,统一报错-CSDN博客
1.创建成功类型以及错误类型的枚举类
package com.ljy.myspringbootlogin.commont;
public enum ErrorCodeEnum {
// 成功
SUCCESS(200, "成功"),
// 40xxx表示请求方原因导致的异常
/**
* 通用异常(400xx)
*/
BUSINESS_EXCEPTION(40000, "业务异常"),
PARAMETER_ERROR(40001, "参数异常"),
/**
* 参数异常(401xx)
*/
MISSING_PARAMETERS(40100, "参数缺失"),
/**
* 用户异常(4021X)
*/
USER_NOT_EXIST(40210, "用户不存在"),
USER_PHONE_NOT_EXIST(40210, "用户手机不存在"),
USER_NAME_DUPLICATE(40211, "用户名称重复"),
USER_DUPLICATE(40212, "用户重复添加"),
USER_ALREADY_BIND(40213, "用户已经绑定微信,重新绑定需退出原绑定微信"),
USER_NO_WORKGROUP(40214, "用户部门没有关联工作组"),
USER_NO_DEPT(40215, "用户没有部门信息"),
USER_DELETE_SELF_ERROR(40216, "您无法删除自己"),
USER_NOT_PHONE(40217, "未获取到有效手机号码,请联系智慧云门户配置"),
USER_NAME_EMPTY(40009, "用户名不能为空"),
USER_PASSWORD_EMPTY(40010, "密码不能为空"),
/**
* 角色异常(4022X)
*/
ROLE_NOT_EXIST(40220, "角色不存在"),
ROLE_NAME_DUPLICATE(40221, "角色名称重复"),
USER_ROLE_DUPLICATE(40222, "用户已关联此角色"),
USER_NO_ROLE(40223, "用户未分配角色,请联系管理员处理"),
REL_ROLE_ERROR(40224, "关联角色失败"),
ROLE_IN_USE(40225, "角色使用中"),
USE_DELETE_ERROR(40226, "无法删除"),
/**
* 部门异常(4023X)
*/
/**
* 认证异常(403xx)
*/
TOKEN_GENERATE_ERROR(40300, "生成token错误"),
LACK_TOKEN(40301, "token缺失"),
AUTHORIZED_TIMEOUT(40302, "token过期"),
LOGIN_ERROR(40303, "用户登录失败"),
NO_LOGGED_IN(40304, "用户未登录"),
UNAUTHORIZED(40305, "接口未授权"),
WITHOUT_AUTHORITY(40001, "用户没有权限"),
ILLEGAL_PARAMETER(40002, "参数非法"),
USER_FROZEN(40005, "用户已冻结"),
USER_EMAIL_DUPLICATE(40007, "用户邮箱重复"),
USER_WITHOUT_DEPARTMENT(40008, "用户没有所属部门"),
USER_PASSWORD_DUPLICATE(40011, "用户新密码与旧密码重复"),
USER_EMAIL_NOT_REGISTERED(40012, "该邮箱未注册"),
ROLE_ASSOCIATE_WITH_USER(40014, "当前角色下存在用户,请为用户分配新角色后删除"),
ROLE_CODE_DUPLICATE(40015, "角色码重复"),
DEPARTMENT_ASSOCIATE_WITH_USER(40017, "当前部门或子部门下存在用户,请为用户分配新部门后删除"),
ILLEGAL_TOKEN(40018, "token非法"),
AUTHENTICATED_TIMEOUT(40019, "认证超时"),
DATE_PARSE_ERROR(40021, "解析日期格式错误,请检查日期格式"),
DEPART_NOT_FOUND(40022, "部门不存在"),
USER_PASSWORD_IS_INCORRECT(40022, "用户或密码不正确"),
WORKING_STATUS(40023, "用户已离职或被冻结"),
ACCOUNT_LOCK(40024, "账号被锁定"),
// 50xxx表示响应方原因导致的异常
RUNTIME_EXCEPTION(50000, "运行时异常"),
SYSTEM_EXCEPTION(50001, "系统异常"),
REDIS_READ_TIMEOUT(50002, "redis数据读取超时"),
REDIS_WRITE_TIMEOUT(50003, "redis数据写入超时"),
MINIO_READ_TIMEOUT(50004, "minio数据读取超时"),
MINIO_WRITE_TIMEOUT(50005, "minio数据写入超时"),
MINIO_READ_ERROR(50006, "minio读取数据失败"),
MINIO_WRITE_ERROR(50007, "minio写入数据失败"),
DATA_CONNECT_ERROR(50008, "数据库连接失败"),
MINIO_CONNECT_ERROR(50008, "minio连接失败"),
MINIO_FILE_NOT_FOUND(500010, "未查询到对应文件记录"),
MINIO_FILE_NAME_TOO_LONG(50041, "文件名称过长,不能超过127个字符"),
MINIO_FILE_SUFFIX_ERROR(50042, "文件后缀名非法"),
MINIO_FILE_SIZE_ERROR(50043, "上传文件过大[单文件大小不得超过:%sMB],如需修改请联系管理员"),
MINIO_FILE_TOTAL_SIZE_ERROR(50044, "上传文件过大[总上传文件大小不得超过:%sMB],如需修改请联系管理员"),
FILE_SIZE_ERROR(50045, "上传文件失败"),
MINIO_PICTURE_FILE_SIZE_ERROR(50046, "上传图片失败,图片大小不得超过:%sMB,如需修改请联系管理员"),
BEAN_CLONE_ERROR(50010, "克隆bean失败"),
BEAN_COPY_ERROR(50011, "复制bean失败"),
DOWNLOAD_ERROR(500020, "下载失败"),
DOWNLOAD_FILE_EMPTY(500021, "下载附件记录为空"),
DOWNLOAD_FILE_NOTFOUND(500022, "未找到下载文件或下载文件已删除"),
// 文件类异常
ANALYSE_FILE_NAME_ERROR(50021, "解析文件名称失败"),
// 压缩类异常
ZIP_FILE_ERROR(50031, "压缩文件失败"),
SQL_ERROR(50201, "系统异常"),
MD5_ERROR(50202, "MD5加密失败"),
URL_PARSE_ERROR(50203, "url编码失败"),
/**
* 系统异常信息
*/
SYSTEM_INSERT_ID_EXIT(60501, "新增系统id必须为空"),
SYSTEM_UPDATE_ID_EXIT(60502, "更新系统id必须不能为空"),
SYSTEM_BASE_NOT_EXIT(60503, "新增|修改系统基础信息不存在"),
;
private final int code;
private final String message;
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
ErrorCodeEnum(int code, String message) {
this.code = code;
this.message = message;
}
public static String getMessageByCode(Integer code) {
for (ErrorCodeEnum codeEnum : ErrorCodeEnum.values()) {
if (codeEnum.getCode() == code) {
return codeEnum.getMessage();
}
}
return "";
}
}
2.创建统一返回类型
package com.ljy.myspringbootlogin.commont;
import java.io.Serializable;
public class Reuslt<T> implements Serializable {
private static final long serialVersionUID = 7498171848815486866L;
/**
* 状态码
*/
private int code;
/**
* 信息
*/
private String msg;
/**
* 数据
*/
private T data;
/**
* 时间戳
*/
private long timestamp ;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Reuslt(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
this.timestamp = System.currentTimeMillis();
}
public Reuslt() {
}
private Reuslt(int code, String msg) {
this(code, msg, null);
}
/**
* 封装请求成功的返回值
*
* @param data 返回值
* @return R
*/
public static <T> Reuslt<T> ok(T data) {
return new Reuslt<>(ErrorCodeEnum.SUCCESS.getCode(), ErrorCodeEnum.SUCCESS.getMessage(), data);
}
/**
* 封装请求失败的返回值
*
* @param errorCode 系统定义的业务错误码和错误信息
* @return R
*/
public static <T> Reuslt<T> error(ErrorCodeEnum errorCode) {
return new Reuslt<>(errorCode.getCode(), errorCode.getMessage());
}
/**
* 封装请求失败的返回值
*
* @param code 自定义业务错误码
* @param message 自定义业务错误信息
* @return R
*/
public static <T> Reuslt<T> error(int code, String message) {
return new Reuslt<>(code, message);
}
/**
* 封装请求失败的返回值(系统定义的业务错误码+自定义业务错误信息)
*
* @param message 自定义业务错误信息
* @return R
*/
public static <T> Reuslt<T> error(String message) {
return new Reuslt<>(ErrorCodeEnum.BUSINESS_EXCEPTION.getCode(), message);
}
}
3.测试
3.1 编写测试controller
package com.ljy.myspringbootlogin.controller;
import com.ljy.myspringbootlogin.commont.Reuslt;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/test")
public class TestController {
//创建登录控制器
@RequestMapping("/test01")
public Reuslt<String> aaa(){
String a="测试";
return Reuslt.ok(a);
}
}
3.1.2 通过浏览器访问
四、配置后端跨域
package com.ljy.myspringbootlogin.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 用于配置跨源资源共享(CORS)策略
* @Configuration:这是一个Spring框架的注解,用于标记当前类是一个配置类,Spring容器在启动时会自动扫描并加载这个配置类
* registry.addMapping("/")**:这行代码表示对所有路径(/**表示匹配所有路径)应用CORS策略
* .allowCredentials(true):允许发送Cookie。默认情况下,出于安全考虑,浏览器不允许跨源请求携带Cookie。设置这个属性为true表示允许携带Cookie
* .allowedOriginPatterns("*"):允许所有原始域进行跨域请求。这里的*表示接受所有域的请求
* .allowedMethods(new String[]{"GET","POST","PUT","DELETE"}):设置允许的HTTP请求方法,这里允许GET、POST、PUT、DELETE方法
* .allowedHeaders("*"):允许所有HTTP头信息
* .exposedHeaders("*"):浏览器可以访问的响应头。这里设置为*表示所有响应头都可以被浏览器访问
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowCredentials(true) //是都发送Cookie
.allowedOriginPatterns("*")//放心哪些原始域
.allowedMethods(new String[]{"GET","POST","PUT","DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}