Spring Boot快速搭建一个简易商城项目【完成登录功能且优化】

完成登录且优化:

未优化做简单的判断:

全部异常抓捕

优化:返回的是json的格式

BusinessException:所有的错误放到这个容器中,全局异常从这个类中调用

BusinessException:
package com.lya.lyaspshop.exception;import com.lya.lyaspshop.resp.JsonResponseStatus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;@EqualsAndHashCode(callSuper = true)//自动生成equals和hashCode方法
@AllArgsConstructor//自动生成全参构造函数
@NoArgsConstructor//自动生成无参构造函数
@Data//自动生成getters、setters、toString
public class BusinessException extends RuntimeException {//    所有的错误放到这个容器中,全局异常从这个类中调用private JsonResponseStatus jsonResponseStatus;}

GlobalExceptionHandler

package com.lya.lyaspshop.exception;import com.lya.lyaspshop.resp.JsonResponseBody;
import com.lya.lyaspshop.resp.JsonResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice//用于声明这个类是一个全局异常处理器
@Slf4j
public class GlobalExceptionHandler {//    已知错误@ExceptionHandler(BusinessException.class)//声明这是一个异常处理方法public JsonResponseBody<?> exceptionBusinessException(BusinessException e) {JsonResponseStatus status = e.getJsonResponseStatus();log.info(status.getMsg());//使用日志打印异常的消息。return JsonResponseBody.other(status);}//    未知错误@ExceptionHandler(Throwable.class)public JsonResponseBody<?> exceptionThrowable(Throwable e) {log.info(e.getMessage());//使用日志打印异常的消息。return JsonResponseBody.other(JsonResponseStatus.UN_KNOWN);}
}

这里为啥要写这两个类:

理解:编写 GlobalExceptionHandler 类可以集中处理应用程序中的各种异常,提高代码的可维护性,同时简化了代码

jsr303

//这里体现了为啥要建这个类:1.降低代码耦合度:VO 实体类可以将数据从数据库实体类中解耦           2.用户进行权限校验等操作,业务逻辑与数据访问层分离开来,提高代码的可读性和可维护性
如果我直接在数据库的实体类中去

<!-- jsr303 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>

实体:使用注解

@NotBlank

抛一个异常:

报错信息:

这个是时候错误已经该变:

连接日志查看:

遇到一个问题:这里就是异常就是使用的303自己带的异常,不要写其他的

前后台的加密过程:

从前台发送请求来:

引入加密js

		<script src="http://www.gongjuji.net/Content/files/jquery.md5.js" type="text/javascript"></script>

加密成功:

加密后数据库的原密码肯定是不对的了。这我们使用debug给截取到密码存入数据库中。

集成redis

<!--        redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>

RedisServiceImpl 

package com.lya.lyaspshop.service.impl;import com.lya.lyaspshop.pojo.User;
import com.lya.lyaspshop.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;@Service
public class RedisServiceImpl implements IRedisService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;//    往redis设置@Overridepublic void setUserToRedis(String token, User user) {redisTemplate.opsForValue().set("user:" + token, user, 7200, TimeUnit.SECONDS);}@Overridepublic User getUserByToken(String token) {return (User) redisTemplate.opsForValue().get("user:" + token);}}

IRedisService

package com.lya.lyaspshop.service;import com.lya.lyaspshop.pojo.User;public interface IRedisService {/*** 将登陆User对象保存到Redis中,并以Token为键*/void setUserToRedis(String token, User user);/*** 根据token令牌获取redis中存储的user对象*/User getUserByToken(String token);}

redisService.setUserToRedis(token, one);

加入cookie

使用CookieUtils类:

package com.lya.lyaspshop.utils;import lombok.extern.slf4j.Slf4j;import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;@Slf4j
public class CookieUtils {/*** @Description: 得到Cookie的值, 不编码*/public static String getCookieValue(HttpServletRequest request, String cookieName) {return getCookieValue(request, cookieName, false);}/*** @Description: 得到Cookie的值*/public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {Cookie[] cookieList = request.getCookies();if (cookieList == null || cookieName == null) {return null;}String retValue = null;try {for (int i = 0; i < cookieList.length; i++) {if (cookieList[i].getName().equals(cookieName)) {if (isDecoder) {retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");} else {retValue = cookieList[i].getValue();}break;}}} catch (UnsupportedEncodingException e) {e.printStackTrace();}return retValue;}/*** @Description: 得到Cookie的值*/public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {Cookie[] cookieList = request.getCookies();if (cookieList == null || cookieName == null) {return null;}String retValue = null;try {for (int i = 0; i < cookieList.length; i++) {if (cookieList[i].getName().equals(cookieName)) {retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);break;}}} catch (UnsupportedEncodingException e) {e.printStackTrace();}return retValue;}/*** @Description: 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码*/public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,String cookieValue) {setCookie(request, response, cookieName, cookieValue, -1);}/*** @param request* @param response* @param cookieName* @param cookieValue* @param cookieMaxage* @Description: 设置Cookie的值 在指定时间内生效,但不编码*/public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,String cookieValue, int cookieMaxage) {setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);}/*** @Description: 设置Cookie的值 不设置生效时间,但编码* 在服务器被创建,返回给客户端,并且保存客户端* 如果设置了SETMAXAGE(int seconds),会把cookie保存在客户端的硬盘中* 如果没有设置,会默认把cookie保存在浏览器的内存中* 一旦设置setPath():只能通过设置的路径才能获取到当前的cookie信息*/public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,String cookieValue, boolean isEncode) {setCookie(request, response, cookieName, cookieValue, -1, isEncode);}/*** @Description: 设置Cookie的值 在指定时间内生效, 编码参数*/public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,String cookieValue, int cookieMaxage, boolean isEncode) {doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);}/*** @Description: 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)*/public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,String cookieValue, int cookieMaxage, String encodeString) {doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);}/*** @Description: 删除Cookie带cookie域名*/public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,String cookieName) {doSetCookie(request, response, cookieName, null, -1, false);}/*** @Description: 设置Cookie的值,并使其在指定时间内生效*/private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {try {if (cookieValue == null) {cookieValue = "";} else if (isEncode) {cookieValue = URLEncoder.encode(cookieValue, "utf-8");}Cookie cookie = new Cookie(cookieName, cookieValue);if (cookieMaxage > 0)cookie.setMaxAge(cookieMaxage);if (null != request) {// 设置域名的cookieString domainName = getDomainName(request);log.info("========== domainName: {} ==========", domainName);if (!"localhost".equals(domainName)) {cookie.setDomain(domainName);}}cookie.setPath("/");response.addCookie(cookie);} catch (Exception e) {e.printStackTrace();}}/*** @Description: 设置Cookie的值,并使其在指定时间内生效*/private static void doSetCookie(HttpServletRequest request, HttpServletResponse response,String cookieName, String cookieValue, int cookieMaxage, String encodeString) {try {if (cookieValue == null) {cookieValue = "";} else {cookieValue = URLEncoder.encode(cookieValue, encodeString);}Cookie cookie = new Cookie(cookieName, cookieValue);if (cookieMaxage > 0)cookie.setMaxAge(cookieMaxage);if (null != request) {// 设置域名的cookieString domainName = getDomainName(request);log.info("========== domainName: {} ==========", domainName);if (!"localhost".equals(domainName)) {cookie.setDomain(domainName);}}cookie.setPath("/");response.addCookie(cookie);} catch (Exception e) {e.printStackTrace();}}/*** @Description: 得到cookie的域名*/private static String getDomainName(HttpServletRequest request) {String domainName = null;String serverName = request.getRequestURL().toString();if (serverName == null || serverName.equals("")) {domainName = "";} else {serverName = serverName.toLowerCase();serverName = serverName.substring(7);final int end = serverName.indexOf("/");serverName = serverName.substring(0, end);if (serverName.indexOf(":") > 0) {String[] ary = serverName.split("\\:");serverName = ary[0];}final String[] domains = serverName.split("\\.");int len = domains.length;if (len > 3 && !isIp(serverName)) {// www.xxx.com.cndomainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];} else if (len <= 3 && len > 1) {// xxx.com or xxx.cndomainName = "." + domains[len - 2] + "." + domains[len - 1];} else {domainName = serverName;}}return domainName;}public static String trimSpaces(String IP) {//去掉IP字符串前后所有的空格while (IP.startsWith(" ")) {IP = IP.substring(1, IP.length()).trim();}while (IP.endsWith(" ")) {IP = IP.substring(0, IP.length() - 1).trim();}return IP;}public static boolean isIp(String IP) {//判断是否是一个IPboolean b = false;IP = trimSpaces(IP);if (IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {String s[] = IP.split("\\.");if (Integer.parseInt(s[0]) < 255)if (Integer.parseInt(s[1]) < 255)if (Integer.parseInt(s[2]) < 255)if (Integer.parseInt(s[3]) < 255)b = true;}return b;}}

自定义注解

根据@isNoblank去写:

这三行代码必须写的:

    boolean require() default false;String expr() default "";String message() default "";

IsMobile
package com.lya.lyaspshop.core;import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;@Documented
@Constraint(validatedBy = {IsMobileConstraintValidator.class})
@Target({FIELD})
@Retention(RUNTIME)
public @interface IsMobile {boolean require() default false;String expr() default "";String message() default "";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}

IsMobileConstraintValidator 

package com.lya.lyaspshop.core;import com.baomidou.mybatisplus.core.toolkit.StringUtils;import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;/*** @author CloudJun*/
public class IsMobileConstraintValidator implements ConstraintValidator<IsMobile, String> {private boolean require;private String expr;@Overridepublic void initialize(IsMobile isMobile) {expr = isMobile.expr();require = isMobile.require();}@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {if (!require) return true;if (StringUtils.isEmpty(value)) return false;return value.matches(expr);}}

优化:定义一个常量类(使用的定值往这里调用就行)

package com.lya.lyaspshop.core;public abstract class Constants {//    常类public static final String EXPR_MOBILE = "(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}";public static final String EXPR_PASSWORD = "[a-zA-Z0-9]{32}";public static final String USER_TOKEN_PREFIX = "user:";}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/587195.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2020年认证杯SPSSPRO杯数学建模A题(第一阶段)听音辨位全过程文档及程序

2020年认证杯SPSSPRO杯数学建模 A题 听音辨位 原题再现&#xff1a; 把若干 (⩾ 1) 支同样型号的麦克风固定安装在一个刚性的枝形架子上 (架子下面带万向轮&#xff0c;在平地上可以被水平推动或旋转&#xff0c;但不会歪斜)&#xff0c;这样的设备称为一个麦克风树。不同的麦…

x-cmd-pkg | 音视频处理领域中常用的开源转换工具:ffmpeg

目录 简介首次用户功能特点类似工具与竞品进一步探索 简介 ffmpeg 是音视频处理领域中常用的开源转换工具。以强大的功能、广泛的格式支持和丰富的参数调节在处理音视频格式的任务中得到了广泛的使用。 FFmpeg 是由 Fabrice Bellard 于 2000 年发起的开源多媒体框架&#xff…

starrocks集群fe/be节点进程守护脚本

自建starrocks集群&#xff0c;有时候服务会挂掉&#xff0c;无法自动拉起服务&#xff0c;于是采用supervisor进行进程守护。可能是版本的原因&#xff0c;supervisor程序总是异常&#xff0c;无法对fe//be进行守护。于是写了个简易脚本。 #!/bin/bash AppNameFecom.starrock…

189. 轮转数组(Java)

题目描述&#xff1a; 给定一个整数数组 nums&#xff0c;将数组中的元素向右轮转 k 个位置&#xff0c;其中 k 是非负数。 输入&#xff1a; nums [1,2,3,4,5,6,7], k 3 输出: [5,6,7,1,2,3,4] 解释: 向右轮转 1 步: [7,1,2,3,4,5,6] 向右轮转 2 步: [6,7,1,2,3,4,5] 向右轮…

多开工具对手机应用启动速度的优化与改进

多开工具对手机应用启动速度的优化与改进 随着智能手机的普及和应用程序的多样化&#xff0c;用户对手机应用的启动速度提出了更高的要求。在这种情况下&#xff0c;多开工具作为一种应用程序管理工具&#xff0c;对手机应用的启动速度进行了优化和改进&#xff0c;为用户带来…

模型 安索夫矩阵

本系列文章 主要是 分享模型&#xff0c;涉及各个领域&#xff0c;重在提升认知。产品市场战略。 1 安索夫矩阵的应用 1.1 江小白的多样化经营策略 使用安索夫矩阵来分析江小白市场战略。具体如下&#xff1a; 根据安索夫矩阵&#xff0c;江小白的现有产品是其白酒产品&…

使用top +jps+jstack定位cpu占用100%的Java服务问题定位简易操作指引

1. 使用top命令找出CPU占用最多的应用 首先&#xff0c;你需要使用top命令来识别哪个进程正在使用大量的CPU资源。 运行top命令:在终端中输入top并按下回车键。查看CPU使用率最高的进程:默认情况下&#xff0c;top会按CPU使用率排序。查看%CPU列&#xff0c;找出使用率最高的…

缓存cache和缓冲buffer的区别

近期被这两个词汇困扰了&#xff0c;感觉有本质的区别&#xff0c;搜了一些资料&#xff0c;整理如下 计算机内部的几个部分图如下 缓存&#xff08;cache&#xff09; https://baike.baidu.com/item/%E7%BC%93%E5%AD%98 提到缓存&#xff08;cache&#xff09;&#xff0c;就…

OpenAI“一路生花”,致力于超级人工智能研发

原创 | 文 BFT机器人 INTELLIGENT ROBOT OpenAI提供1000万美元的资助用于解决超级智能AI控制问题 OpenAI是人工智能研究领域的领先组织&#xff0c;据媒体称&#xff0c;它正在采取积极措施应对与超级智能AI系统相关的潜在风险。在一项大胆的举措中&#xff0c;该公司宣布将提…

独立站如何优化网页加载速度

对于跨境电商独立站而言&#xff0c;流量是跨境电商业务的重中之重&#xff0c;由于独立站并不自带流量&#xff0c;非常依赖于谷歌搜索引擎自然流量&#xff0c;以及付费广告流量。 但随着付费流量价格日益水涨船高&#xff0c;为了摆脱对付费流量的依赖&#xff0c;相信广大…

可移动磁盘上的文件删除了怎么恢复?详细教程介绍

在我们的日常生活和工作中&#xff0c;可移动磁盘作为一种便携式的存储设备&#xff0c;经常被用来备份和传输数据。然而&#xff0c;有时候由于误操作或不小心的删除&#xff0c;导致可移动磁盘上的文件丢失。这些文件可能包含重要的工作资料、个人照片、视频等&#xff0c;一…

【YOLO系列】YOLOv8 -【教AI的陶老师】

文章目录 yolo v8 模型结构图这样搞有什么意义&#xff1f;【获得不同尺寸的输出】c2f 详细结构yolo v8 损失函数与 yolo v5 的区别 yolo v8 模型结构图 详细结构图 这样搞有什么意义&#xff1f;【获得不同尺寸的输出】 c2f 详细结构 yolo v8 损失函数 与 yolo v5 的区别

超声波测距系统

文章目录 前言一、功能描述一、界面一二、界面二三、界面三四、界面四五、初始界面 二、编程实现 前言 具有测距、温度补充、实时时钟、记忆、阈值警报、串口数据发送等等功能&#xff0c;通过LCD1602显示&#xff0c;按键进行相关操作。 一、功能描述 LCD1602显示共有五个界面…

第1章 Kali Linux入门

本章将带领读者初步了解渗透测试专用的独立Linux 操作系统——Kali Linux。本章涵盖下述主题&#xff1a; ● Kali 的发展简史&#xff1b; ● Kali 的一般用途&#xff1b; ● Kali 的下载与安装&#xff1b; ● Kali 的配置与更新。 在本章的结尾部分&#xff0c;我们还…

【进阶】【JS逆向爬虫】【2.JavaScript 基础语法】JS代码导入方式

JS逆向爬虫 JS代码导入方式1.行内式写法2.内嵌式&#xff08;建议写在</body>之前&#xff09;3.外部式&#xff08;建议写在</head>之前&#xff09; JS代码导入方式 1.行内式写法 可以将单行或少量 JS 代码写在HTML标签的事件属性中&#xff08;以 on 开头的属…

centos安装Docker和DockerCompose

Docker CE 支持 64 位版本 CentOS 7&#xff0c;并且要求内核版本不低于 3.10&#xff0c; CentOS 7 满足最低内核的要求&#xff0c;所以我们在CentOS 7安装Docker。 安装Docker 卸载旧版docker 旧版本的 Docker 采用docker或docker-engine。在尝试安装新版本之前卸载任何此…

GitHub提交项目到仓库fatal: No configured push destination.

原因&#xff1a;没指定提交到哪个远程仓库 解决方法&#xff1a; 在你git add .和commit之后 git add . git commit -m "信息" git push前输入以命令 git branch -M main git remote add origin gitgithub.com:xxx(你GitHub的名称)/xxx.git(你仓库的名称) git …

【计算机网络】第五,六章摘要重点

1.运输层协议概述 运输层提供的是进程之间的通信 2. 3.套接字指的是什么 ip地址端口号 4.每一条TCP语句唯一地被通信两端连接的两个端点 5.TCP传输如何实现 以字节为单位的滑动窗口 超时重传 选择确认 6.TCP流量控制和拥塞控制的区别 流量控制&#xff1a;点对点通信…

Cisco模拟器-OSPF路由协议

设计要求用两台双口路由器连接不同IP网段的计算机&#xff0c;并使用OSFP协议发现路由表使不同IP网段的计算机可以相互通信。 通过设计&#xff0c;可以连通IP地址网段不同的局域网&#xff0c;可应用在园区网的互连和互通的实现上。 主要配置步骤 路由器0&#xff1a; Router…

【PostgreSQL】从零开始:(三十九)约束-主键

主键 主键&#xff08;Primary Key&#xff09;是数据库表中用于唯一标识每一行记录的字段。主键具有以下特点&#xff1a; 唯一性&#xff1a;每个主键值在表中是唯一的&#xff0c;不允许出现重复值。非空性&#xff1a;主键字段的值不能为空&#xff0c;即主键字段不能为n…