Springboot初始化項目並完成登入註冊的全過程
idea spring Initializr創建項目
勾選項目所需要的依賴
pom.xml
文件會加載勾選的依賴,也可以不勾選後面通過自己常用的pom.xml
統一導入。
- Lombok 可以通過註解省去一些get,set方法。
簡單項目常用pom.xml:
mybatis-plus、mybatis、
<?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.7.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example.community</groupId> <artifactId>springboot03</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot03</name> <description>springboot03</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.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </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> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.13</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
整體項目結構
創建User實體類放入Enity下
@TableName("user")
是實體對應的表的名字
@TableId(type = IdType.AUTO)
表的主鍵
@TableField(exist = false)
不存在,就不會返回空。
package com.example.community.enity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Integer userId; private String email; private String username; private String password; private String avatar; private String phone; @TableField(exist = false) private String code; public User(String email, String password) { this.email = email; this.password = password; } }
創建通用返回的結果類
可以使用泛型傳入對應的實體類,這裡我就不傳瞭。
package com.example.community.common; import lombok.Data; @Data public class R { private Integer code; private String msg; private Object data; public R(Integer code, String msg, Object ob) { this.code = code; this.msg = msg; this.data = ob; } public R(Integer code, String msg) { this.code = code; this.msg = msg; } public static R success(String msg){ R r= new R(1,msg); return r; } public static R success(String msg,Object ob){ R r= new R(1,msg,ob); return r; } public static R error(String msg){ R r= new R(0,msg,null); return r; } }
創建controller
在controller裡可以對前端的請求進行一個分發,處理。根據地址鏈接找到對應的controller。
登入模塊,可以創建一個UserController
處理用戶的相關信息。
package com.example.community.controller; import com.example.community.common.R; import com.example.community.enity.User; import com.example.community.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.Map; @Slf4j @RestController() @RequestMapping("/user") @CrossOrigin(origins = {"http://localhost:8090", "null"}) public class UserController { @Autowired UserService service; @PostMapping("/login") public R login(@RequestBody User user) { log.info("user"+user.toString()); return service.login(user.getEmail(), user.getPassword()); } @PostMapping("/register") @ResponseBody public R register(@RequestBody Map<String, Object> data, HttpSession session) { log.info(data.toString()); String code1 = (String) session.getAttribute("code"); String email1 = (String) session.getAttribute("email"); log.info("---------------------------"); log.info(email1); log.info(code1); log.info("---------------------------"); if(code1 == null || email1 == null){ return R.error("驗證碼已過期或郵箱有誤"); } if (!data.get("password").equals(data.get("password_confirmation"))) { return R.error("兩次密碼不一致"); } if (!email1.equals(data.get("email").toString())) { return R.error("郵箱錯誤"); } if (!code1.equals(data.get("code").toString())) { return R.error("驗證碼錯誤"); } User user1 = new User(data.get("email").toString(), data.get("password").toString()); return service.register(user1); } }
創建service層
service
層給controller
層提供服務,調用dao
層mapper
查詢數據庫的數據,提供相對應的服務。
在這裡我是用瞭mybtis-plus
來進行數據庫簡單的查詢。
用戶模塊的service層代碼:
UserService
接口
繼承mybatis-plus
的IService
package com.example.community.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.community.common.R; import com.example.community.enity.User; public interface UserService extends IService<User> { public R selectUserByUsername(String name); public R login(String username, String password); public R register(User user); public R logout(String token); }
UserService
實現類
在這個類中,調用瞭mapper提供的方法。
繼承ServiceImpl
package com.example.community.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.community.Mapper.UserMapper; import com.example.community.common.R; import com.example.community.enity.User; import com.example.community.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Autowired private UserMapper userMapper; @Override public R selectUserByUsername(String name){ return null; } @Override public R login(String email, String password){ User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email)); if(user == null){ return R.error("用戶不存在"); } if(!user.getPassword().equals(password)){ return R.error("密碼錯誤"); } return R.success("登錄成功"); } @Override public R register(User user){ User user1 = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername())); if(user1 != null){ return R.error("用戶已存在"); } userMapper.insert(user); return R.success("註冊成功"); } @Override public R logout(String token){ return null; } }
創建Mapper / Dao層
使用瞭mybatis-plus
,所以隻需要繼承BaseMapper
既可。
package com.example.community.Mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.community.enity.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { }
郵箱驗證碼、生成Token
- 使用郵箱進行登入驗證碼驗證
- 使用
jwt
生成token
返回給前端,服務端可以用來判斷用戶是否登入。並且支持跨域
實現這兩個功能需要使用到一些工具類和配置,如下:
package com.example.community.utils; import io.jsonwebtoken.Jwt; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.HashMap; import java.util.Map; public class JWTUtils { private static final String jwtToken = "123456Mszlu!@#$$"; public static String createToken(Long userId) { Map<String, Object> claims = new HashMap<>(); claims.put("userId", userId); JwtBuilder jwtBuilder = Jwts.builder() .signWith(SignatureAlgorithm.HS256, jwtToken) // 簽發算法,秘鑰為jwtToken .setClaims(claims) // body數據,要唯一,自行設置 .setIssuedAt(new Date()) // 設置簽發時間 .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000));// 一天的有效時間 String token = jwtBuilder.compact(); return token; } public static Map<String, Object> checkToken(String token) { try { Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token); return (Map<String, Object>) parse.getBody(); } catch (Exception e) { e.printStackTrace(); } return null; } }
攔截器的配置
package com.example.community.handler; import com.alibaba.druid.util.StringUtils; import com.example.community.common.R; import com.example.community.utils.JsonUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component @Slf4j public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{ log.info("請求被攔截{}",request); if(!(handler instanceof HandlerMethod)){ return true; } String token = request.getHeader("Authorization"); log.info("token:{}",token); if(StringUtils.isEmpty(token)){ R r= R.error("未登錄"); response.setContentType("application/json;charset=utf-8"); log.info("{}",r); response.getWriter().print(JsonUtil.objectToJson(r)); return false; } return true; } }
package com.example.community.config; import com.example.community.handler.LoginInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 用戶攔截器 registry.addInterceptor(new LoginInterceptor()) // 需要攔截的請求 .addPathPatterns("/user/**","/article/**") // 需要放行的請求 .excludePathPatterns("/user/login","/user/register","/mail/**") // 添加swagger-ui的放行路徑 .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html/**") ; } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .maxAge(3600) .allowCredentials(true); } }
實現郵箱認證登入,之前寫過一個,傳送門
總結
到此這篇關於Springboot初始化項目並完成登入註冊的文章就介紹到這瞭,更多相關Springboot初始化項目並登入註冊內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- springboot+mybatis-plus實現內置的CRUD使用詳解
- SpringBoot數據校驗功能的實現
- SpringBoot整合Redis將對象寫入redis的實現
- springboot表單提交之validator校驗
- SpringBoot集成JWT實現登陸驗證的方法詳解