从零开始搭建日志系统(2)-项目初始化
程序员文章站
2022-05-13 08:15:16
...
git项目地址
git地址
https://github.com/MrITzhongzi/blog-system.git
项目初始化
- 配置项目的maven仓库,git仓库等等
- 从数据库反向生成实体类
- 配置好mysql
- 加入 mybatis
- 实现 JsonBuild和JWTUtils工具类
注意事项
- 注解说明 示例代码
/**
* @description: 用户模块
* @author: lihongwei
* @time: 2020/4/8 1:42 下午
*/
@RestController
@RequestMapping("/api/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping(path = "register", method = RequestMethod.POST)
public JsonBuilder userRegister(@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "password", required = true) String password,
@RequestParam(value = "phone", required = true) String phone,
@RequestParam(value = "nickname", required = true) String nickname){
// 从数据库查询有没有此用户,有的话返回错误,没有继续
List<LhwUser> userList = userService.queryAllUser();
if(userList.size() > 0) {
return JsonBuilder.buildError("用户已经存在");
}
// 校验 各个字段是否符合要求
// 密码加密,存入数据库
// 使用jwt成成**
return JsonBuilder.buildSuccess();
}
}
@RestController
表示该controller返回一个 json数据@RequestMapping("/api/user")
定义了访问该类的前缀路径,也可以不设置@RequestMapping(path = "register", method = RequestMethod.POST)
定义了访问该方法的最终路径
/**
* @description:
* @author: lihongwei
* @time: 2020/4/8 3:26 下午
*/
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public int insert(LhwUser user) {
int num = userMapper.insert(user);
return num;
}
@Override
public List<LhwUser> queryAllUser() {
return userMapper.queryAllUser();
}
}
@Service
标记该类是一个 service服务,springboot容器会自动注入
- mybatis集成
- 加入依赖工具
<!-- 引入mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
- 在入口方法上加上 mapperscan扫描 mapper类
@SpringBootApplication
@MapperScan("com.lhw.blog.mapper")
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}
- 在mapper类上增加 component组件注解,使springboot容器可以找到
package com.lhw.blog.mapper;
import com.lhw.blog.domain.LhwUser;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @description: 用户 mapper 用户的增删改查
* @author: lihongwei
* @time: 2020/4/8 3:19 下午
*/
@Component
public interface UserMapper {
@Insert("insert into lhw_user(user_ip, user_name, user_password, user_nickname) values (#{userIp}, #{userName},#{userPassword},#{userNickname})")
int insert(LhwUser user);
@Select("select * from lhw_user")
List<LhwUser> queryAllUser();
}
注意: 如果某个类忘记加 @component 或者 @Service 方法,springboot容器会报
该类找不到的错误
JsonBuild工具
package com.lhw.blog.tool;
import javax.swing.*;
/**
* @description: 控制返回json格式
* @author: lihongwei
* @time: 2020/4/8 1:58 下午
*/
public class JsonBuilder {
public JsonBuilder(){
}
public JsonBuilder(int code) {
this.code = code;
}
public JsonBuilder(int code, String description){
this.code = code;
this.description = description;
}
public JsonBuilder(int code, String description, Object data){
this.code = code;
this.description = description;
this.data = data;
}
public int code;
public String description;
public Object data;
public static JsonBuilder buildSuccess(){
return new JsonBuilder(0, "success", null);
}
public static JsonBuilder buildSuccess(int code){
return new JsonBuilder(code, "success", null);
}
public static JsonBuilder buildSuccess(String description){
return new JsonBuilder(0, description, null);
}
public static JsonBuilder buildSuccess(Object data){
return new JsonBuilder(0, "success", data);
}
public static JsonBuilder buildSuccess(int code, String description){
return new JsonBuilder(code, description, null);
}
public static JsonBuilder buildSuccess(int code, Object data){
return new JsonBuilder(code, "success", data);
}
public static JsonBuilder buildSuccess(String description, Object data){
return new JsonBuilder(0, description, data);
}
public static JsonBuilder buildSuccess(int code, String description, Object data){
return new JsonBuilder(code, description, data);
}
public static JsonBuilder buildError(){
return new JsonBuilder(-1, "error", null);
}
public static JsonBuilder buildError(int code){
return new JsonBuilder(code, "error", null);
}
public static JsonBuilder buildError(String description){
return new JsonBuilder(-1, description, null);
}
public static JsonBuilder buildError(Object data){
return new JsonBuilder(-1, "error", data);
}
public static JsonBuilder buildError(int code, String description){
return new JsonBuilder(code, description, null);
}
public static JsonBuilder buildError(int code, Object data){
return new JsonBuilder(code, "error", data);
}
public static JsonBuilder buildError(String description, Object data){
return new JsonBuilder(-1, description, data);
}
public static JsonBuilder buildError(int code, String description, Object data){
return new JsonBuilder(code, description, data);
}
}
JWTUtils JWT工具
package com.lhw.blog.tool;
import com.lhw.blog.domain.LhwUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import java.util.Date;
/**
* @description: 用于生成和解析JWT
* @author: lihongwei
* @time: 2020/4/8 4:01 下午
*/
public class JWTUtils {
/**
* **
*/
@Value("${jwt.secret}")
private static String secret;
/**
* 过期时间
*/
@Value("${jwt.expire}")
private static long expire;
@Value("${jwt.subject}")
private static String subject;
/**
* 生成JWTtoken
* @param user
* @return
*/
public static String generateToken(LhwUser user){
if(user == null || user.getUserId() == null || user.getUserNickname() ==null || user.getUserTelephoneNumber() == null || user.getUserPassword() == null ) {
return null;
}
String jwtToken = Jwts.builder().setSubject(subject)
.claim("id", user.getUserId())
.claim("nickname", user.getUserNickname())
.claim("phone", user.getUserTelephoneNumber())
.claim("password", user.getUserPassword())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expire))
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
return jwtToken;
}
/**
* 检验 token
* @param token
* @return
*/
public static Claims checkJWT(String token) {
try {
Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
return body;
} catch (Exception e) { }
return null;
}
}
密码加密工具
package com.lhw.blog.tool;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @description:
* @author: lihongwei
* @time: 2020/4/8 4:59 下午
*/
public class SecretUtils {
/**
* 字符串加密
* @param oldPwd
* @return
*/
public static String generatePwd(String oldPwd) throws NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA");
// 生成32位字符串秘文
return new BigInteger(sha.digest()).toString(32);
}
}
现在的pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lhw</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>blog</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 引入mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MySQL的JDBC驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version> 8.0.19</version>
</dependency>
<!-- JWT工具类 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
上一篇: 一天一模式之21装饰器模式
下一篇: Linux学习:基本命令(二)