【SSM】登录和注册

news/2025/1/13 3:15:40/

框架

  • controller 控制层

  • dao 持久层

  • interceptor 拦截器

  • model 实体层

  • uils 工具类

  • service 业务层

  • resources 资源文件层

    • mapper 放编写sql语句的文件,与持久层的文件对应

具体代码

@Controller
//控制层
public class UserController {
//用于调用Service层方法@Autowiredprivate IUserService userService;
//注册@RequestMapping(value = "/register",method = RequestMethod.POST)@ResponseBodypublic Result register(@RequestBody User user){return userService.register(user);}
//登录@RequestMapping(value = "/login",method = RequestMethod.POST)@ResponseBodypublic Result login(@RequestBody User user){return userService.login(user);}
//注销@RequestMapping(value = "/logout")@ResponseBodypublic Result logout(@RequestHeader("token") String token){return userService.logout(token);}
//用于展示首页@RequestMapping(value = "/show")@ResponseBodypublic Result show(){return Result.ok("成功","首页");}}
//持久层
//状态码方法
public interface TokenMapper {
//保存到数据库int insert(@Param("token") String token, @Param("userid") int id);
//查看Integer selectByToken(String token);
//删除void deleteByToken(String token);
}
//用户数据库
public interface UserMapper {
//插入数据,也就是注册的int insert(User user);
//通过username查询,用于注册查重User findUserByUsername(String username);
//登录方法User findUserByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}
//拦截器
@Controller
public class UserInterceptor implements HandlerInterceptor {
//调用持久层的方法@Autowiredprivate TokenMapper tokenMapper;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//获取状态码String token = request.getHeader("token");//如果状态码不为空或者空字符串if (token!=null&&token!=""){Integer id = tokenMapper.selectByToken(token);//如果不为空且查到存在状态码返回trueif (id!=null&&id>0){return true;}}//反之就是权限不够String string = JSON.toJSONString(Result.error(500, "权限不够"));response.getWriter().println(string);return false;}
//后置@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);}
//最终@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {HandlerInterceptor.super.afterCompletion(request, response, handler, ex);}
}
public class Result<T> implements Serializable {
//返回状态private static final long serialVersionUID = 1L;/*** 成功标志*/private boolean success = true;/*** 返回处理消息*/private String message = "操作成功!";/*** 状态码*/private Integer code = 0;/*** 返回数据对象 data*/private T result;public static long getSerialVersionUID() {return serialVersionUID;}public boolean isSuccess() {return success;}public void setSuccess(boolean success) {this.success = success;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public T getResult() {return result;}public void setResult(T result) {this.result = result;}public long getTimestamp() {return timestamp;}public void setTimestamp(long timestamp) {this.timestamp = timestamp;}/*** 时间戳*/private long timestamp = System.currentTimeMillis();public Result() {}public Result<T> success(String message) {this.message = message;this.code = 200;this.success = true;return this;}public static Result<Object> ok() {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);r.setMessage("成功");return r;}public static Result<Object> ok(String msg) {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);r.setMessage(msg);return r;}public static Result<Object> ok(String msg,Object obj) {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);r.setMessage(msg);r.setResult(obj);return r;}public static Result<Object> ok(Object data) {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);r.setMessage("成功");r.setResult(data);return r;}public static Result<Object> error(String msg) {return error(500, msg);}public static Result<Object> error(int code, String msg) {Result<Object> r = new Result<Object>();r.setCode(code);r.setMessage(msg);r.setSuccess(false);return r;}public Result<T> error500(String message) {this.message = message;this.code = 500;this.success = false;return this;}/*** 无权限访问返回结果*/public static Result<Object> noauth(String msg) {return error(555, msg);}
}
//user实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {/*** 这是id*/private int id;/*** 这是昵称*/private String nickname;/*** 这是用户名*/private String username;/*** 这是密码*/private String password;/*** 这是年龄*/private int age;/*** 这是手机号*/private String phone;
}
//service接口
public interface IUserService {Result register(User user);Result login(User user);Result logout(String token);
}
//实现service接口
@Service
@Transactional
public class UserService implements IUserService {@Autowiredprivate UserMapper userMapper;@Autowiredprivate TokenMapper tokenMapper;/*** 注册* */@Overridepublic Result register(User user) {//用户名校验String username = user.getUsername();if (username != null && username != "") {boolean check = RegUtils.check(username, "^(?=[a-zA-Z])(?!.*[\\-_]{2})[a-zA-Z0-9\\-_]{8,12}$");if (!check){return Result.error("用户名格式不正确");}}else {return Result.error("用户名不能为空");}
//        是否被注册过User user1 = userMapper.findUserByUsername(username);if (user1!=null){return Result.error("用户名已存在,请重新输入");}
//        密码校验String password = user.getPassword();if (password != null && password != "") {boolean check = RegUtils.check(password, "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]).{8,}$");if (!check){return Result.error("密码格式不正确");}}else {return Result.error("密码不能为空");}
//        年龄校验int age = user.getAge();if(age>120||age<18){return Result.error("年龄不符合要求");}//手机号的校验String phone = user.getPhone();if (phone != null && phone != "") {boolean check = RegUtils.check(phone, "^(1[3-9]\\d{9}$)");if (!check){return Result.error("手机号格式不正确");}}else {return Result.error("手机号不能为空");}
//        写入数据库user.setPassword(MD5Utils.encrypt(password));int insert = userMapper.insert(user);return insert > 0 ? Result.ok("注册成功") : Result.error("注册失败");}/*** 登录*/@Overridepublic Result login(User user) {String username = user.getUsername();if (username != null && username != "") {boolean check = RegUtils.check(username, "^(?=[a-zA-Z])(?!.*[\\-_]{2})[a-zA-Z0-9\\-_]{8,12}$");if (!check) {return Result.error("用户名格式不正确");}} else {return Result.error("用户名不能为空");}String password = user.getPassword();if (password != null && password != "") {boolean check = RegUtils.check(password, "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]).{8,16}$");if (!check) {return Result.error("密码格式不正确");}} else {return Result.error("密码不能为空");}password = MD5Utils.encrypt(password);User user1 = userMapper.findUserByUsernameAndPassword(username, password);if(user1!=null){String uuid = UUID.randomUUID().toString();String token = uuid.replace("-", "");tokenMapper.insert(token, user1.getId());return Result.ok("登录成功", token);}return Result.error("登录失败");}
//注销@Overridepublic Result logout(String token) {if(token!=null && token!=""){tokenMapper.deleteByToken(token);}return Result.ok("注销成功");}
}
//正则表达式
public class RegUtils {public static boolean check(String target,String regex) {// 正则表达式Pattern pattern = Pattern.compile(regex);// 匹配器Matcher matcher = pattern.matcher(target);// 匹配if (matcher.matches()) {return true;}return false;}
}//MD5
public static String encrypt(String password){MessageDigest md = null;String s = null;try {md = MessageDigest.getInstance("MD5");md.update(password.getBytes());s = new BigInteger(1, md.digest()).toString(16);} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return s;}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xinzhi.dao.TokenMapper"><insert id="insert">insert into token (token,userid) values (#{token},#{userid})</insert><delete id="deleteByToken">delete from token where token=#{token}</delete><select id="selectByToken" resultType="java.lang.Integer">select id from token where token=#{token}</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.LiMou.dao.UserMapper"><sql id="userAll">id,nickname,username,password,age,phone</sql><insert id="insert">insert into user (nickname,username,password,age,phone) values (#{nickname},#{username},#{password},#{age},#{phone})</insert><select id="findUserByUsername" resultType="com.xinzhi.model.User">select <include refid="userAll"/> from user where username=#{username}</select><select id="findUserByUsernameAndPassword" resultType="com.xinzhi.model.User">select <include refid="userAll"/> from user where username=#{username} and password=#{password}</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!--加载properties文件--><context:property-placeholder location="classpath:db.properties"/><!--数据源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${name}"/><property name="password" value="${password}"/></bean><!--开启bean注解扫描--><context:component-scan base-package="com.LiMou"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!--事务管理器--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--开启注解式事务--><tx:annotation-driven transaction-manager="txManager"/><!--整合mybatis到spring中--><bean class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="typeAliasesPackage" value="com.xinzhi.model"/><property name="mapperLocations" value="classpath:mapper/*.xml"/><!--分页插件--><property name="plugins"><array><bean class="com.github.pagehelper.PageInterceptor"><property name="properties"><props><prop key="helperDialect">mysql</prop><prop key="reasonable">true</prop></props></property></bean></array></property></bean><!--映射扫描--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.LiMou.dao"/></bean></beans>

db.properties//连接数据库的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.xinzhi.controller"/><mvc:annotation-driven ><!-- 消息转换器 --><mvc:message-converters register-defaults="true"><bean class="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes" value="text/plain;charset=UTF-8"/></bean></mvc:message-converters></mvc:annotation-driven><!--    视图解析器--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/page/"/><property name="suffix" value=".jsp"/></bean><!--    多媒体解析器--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"/><property name="maxUploadSize" value="500000"/></bean><mvc:interceptors><mvc:interceptor><mvc:mapping path="/**"/><mvc:exclude-mapping path="/register"/><mvc:exclude-mapping path="/login"/><bean class="com.xinzhi.interceptor.UserInterceptor"/></mvc:interceptor></mvc:interceptors></beans>

//依赖
<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/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.xinzhi</groupId><artifactId>conformity1</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>conformity1 Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version></dependency><!--mysql环境--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.31</version></dependency><!--spring整合jdbc--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.9.RELEASE</version></dependency><!--spring整合mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.3</version></dependency><!--druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><!--分页插件坐标--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.2</version></dependency><!--springmvc环境--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.9.RELEASE</version></dependency><!--jackson相关坐标3--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency><!--servlet环境--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><!--junit单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--spring整合junit--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.4</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>3.3.2</version></plugin></plugins><finalName>conformity1</finalName></build>
</project>

http://www.ppmy.cn/news/1116660.html

相关文章

【音视频】H264视频压缩格式

H264简介 H.264从1999年开始&#xff0c;到2003年形成草案&#xff0c;最后在2007年定稿有待核实。在ITU的标准里称为H.264, 在MPEG的标准里是MPEG-4的一个组成部分-MPEG-4 Part 10&#xff0c;又叫Advanced Video Codec&#xff0c;因此常常称为MPEG-4AVC或直接叫AVC。 压缩算…

2000-2018年各省能源消费和碳排放数据

2000-2018年各省能源消费和碳排放数据 1、时间&#xff1a;2000-2018年 2、范围&#xff1a;30个省市 3、指标&#xff1a;id、year、ENERGY、COAL、碳排放倒数*100 4、来源&#xff1a;能源年鉴 5、指标解释&#xff1a; 2018年碳排放和能源数据为插值法推算得到 碳排放…

[考前速记] 最大公约数与最大公倍数

最大公约数 int gcd(int a,int b){if (b0)return a;else return gcd(b,a%b); } 熟练了可以写成&#xff1a; int gcd(int a,int b){return b ? gcd(b,a%b):a; } 值得注意的是&#xff1a;让a和b均为非负数&#xff0c;可以使用algorithm下的abs(int x)和cmath下的fabs(dou…

会话控制学习

文章目录 介绍cookieexpress中使用cookie获取cookie session配置区别 介绍 cookie express中使用cookie 退出登录就是删除cookie 获取cookie 添加中间键后&#xff0c;直接获取 session 配置 区别

异步FIFO设计的仿真与综合技术(6)

概述 本文主体翻译自C. E. Cummings and S. Design, “Simulation and Synthesis Techniques for Asynchronous FIFO Design 一文&#xff0c;添加了笔者的个人理解与注释&#xff0c;文中蓝色部分为笔者注或意译。前文链接&#xff1a; 异步FIFO设计的仿真与综合技术&#xf…

day3_QT

day3_QT 1、文件保存2、始终事件 -闹钟 1、文件保存 2、始终事件 -闹钟 widget.h #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QTimerEvent> #include <QTime> #include <QTextToSpeech>QT_BEGIN_NAMESPACE namespace Ui { clas…

腾讯视频共享设备ip会不会出现错误

腾讯视频共享设备功能为用户提供了方便的多屏互动体验&#xff0c;然而在使用该功能时&#xff0c;一些用户可能会遇到IP地址错误的问题。IP地址错误可能导致共享设备无法正常连接或通信。本文旨在对腾讯视频共享设备IP错误问题进行分析和解答&#xff0c;帮助读者更好地理解可…

OpenHarmony AI框架开发指导

一、概述 1、功能简介 AI 业务子系统是 OpenHarmony 提供原生的分布式 AI 能力的子系统。AI 业务子系统提供了统一的 AI 引擎框架&#xff0c;实现算法能力快速插件化集成。 AI 引擎框架主要包含插件管理、模块管理和通信管理模块&#xff0c;完成对 AI 算法能力的生命周期管理…