项目结构图:
Maven配置环境:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <!--java-jwt坐标--> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> </dependencies>
application的配置文件:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/big_event?serverTimezone=UTC username: xxxx password: xxxx mybatis: configuration: map-underscore-to-camel-case: true #开启驼峰命名和下划线命名的自动转换 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
bean层代码:User文件的代码
package worldtolingyidianke.file.bean; import lombok.Data; import java.time.LocalDateTime; //lombok 在编译阶段,为实体类自动生成setter getter toString // pom文件中引入依赖 在实体类上添加注解 @Data public class User { private Integer id;//主键ID private String username;//用户名 //让springmvc把当前对象转换成json字符串的时候,忽略password,最终的json字符串中就没有password这个属性了 private String password;//密码 private String nickname;//昵称 private String email;//邮箱 private String userPic;//用户头像地址 private LocalDateTime createTime;//创建时间 private LocalDateTime updateTime;//更新时间 }
bean中Result
package worldtolingyidianke.file.bean; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Data; //统一响应结果 @NoArgsConstructor @AllArgsConstructor @Data public class Result<T> { private Integer code;//业务状态码 0-成功 1-失败 private String message;//提示信息 private T data;//响应数据 //快速返回操作成功响应结果(带响应数据) //快速返回操作成功响应结果(带响应数据) public static <E> Result<E> success(E data) { return new Result<>(0, "操作成功", data); } //快速返回操作成功响应结果 public static Result success() { return new Result(0, "操作成功", null); } public static Result error(String message) { return new Result(1, message, null); } }
controller层代码:UserController代码
package worldtolingyidianke.file.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import worldtolingyidianke.file.bean.Result; import worldtolingyidianke.file.bean.User; import worldtolingyidianke.file.service.UserService; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/register") public Result register(String username,String password){ User u = userService.findByUserName(username); if (u == null) { //没有占用 //注册 userService.register(username, password); return Result.success(); } else { //占用 return Result.error("用户名已被占用"); } } }
exception
package worldtolingyidianke.file.exception; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import worldtolingyidianke.file.bean.Result; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public Result handleException(Exception e){ e.printStackTrace(); return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败"); } }
mappers,UserMapper的代码
package worldtolingyidianke.file.mappers; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import worldtolingyidianke.file.bean.User; @Mapper public interface UserMapper { // 根据用户名查询用户 @Select("select * from user where username=#{username}") User findByUserName(String username); // 根据用户名进行添加, @Insert("insert into user(username,password,create_time,update_time)" + " values(#{username},#{password},now(),now())") void add(String username, String password); }
service
UserService接口的代码
package worldtolingyidianke.file.service; import worldtolingyidianke.file.bean.User; public interface UserService { // 根据用户名查询用户 User findByUserName(String username); //注册 void register(String username, String password); }
impl的代码UserServiceImpl
package worldtolingyidianke.file.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import worldtolingyidianke.file.bean.User; import worldtolingyidianke.file.mappers.UserMapper; import worldtolingyidianke.file.service.UserService; import worldtolingyidianke.file.util.Md5Util; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User findByUserName(String username) { User u = userMapper.findByUserName(username); return u; } @Override public void register(String username,String password) { String md5String = Md5Util.getMD5String(password); //添加 userMapper.add(username,md5String); } }
util的工具类:
Md5Util工具类
package worldtolingyidianke.file.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Md5Util { /** * 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合 */ protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; protected static MessageDigest messagedigest = null; static { try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsaex) { System.err.println(Md5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。"); nsaex.printStackTrace(); } } /** * 生成字符串的md5校验值 * * @param s * @return */ public static String getMD5String(String s) { return getMD5String(s.getBytes()); } /** * 判断字符串的md5校验码是否与一个已知的md5码相匹配 * * @param password 要校验的字符串 * @param md5PwdStr 已知的md5校验码 * @return */ public static boolean checkPassword(String password, String md5PwdStr) { String s = getMD5String(password); return s.equals(md5PwdStr); } public static String getMD5String(byte[] bytes) { messagedigest.update(bytes); return bufferToHex(messagedigest.digest()); } private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); } private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); } private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同 char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换 stringbuffer.append(c0); stringbuffer.append(c1); } }
ThreadLocalUtil
package worldtolingyidianke.file.util; /** * ThreadLocal 工具类 */ @SuppressWarnings("all") public class ThreadLocalUtil { //提供ThreadLocal对象, private static final ThreadLocal THREAD_LOCAL = new ThreadLocal(); //根据键获取值 public static <T> T get(){ return (T) THREAD_LOCAL.get(); } //存储键值对 public static void set(Object value){ THREAD_LOCAL.set(value); } //清除ThreadLocal 防止内存泄漏 public static void remove(){ THREAD_LOCAL.remove(); } }
DemoApplication的文件:
package worldtolingyidianke.file; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
resources下的Mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="worldtolingyidianke.file.mappers.ArticleMapper"> <!--动态sql--> <select id="list" resultType="worldtolingyidianke.file.bean.Article"> select * from article <where> <if test="categoryId!=null"> category_id=#{categoryId} </if> <if test="state!=null"> and state=#{state} </if> and create_user=#{userId} </where> </select> </mapper>