SpringBoot+Vue博客系统---后端接口开发
Java后端接口開發(fā)
從零開始搭建一個項目骨架,最好選擇合適,熟悉的技術(shù),并且在未來易拓展,適合微服務(wù)化體系等。所以一般以Springboot作為我們的框架基礎(chǔ),這是離不開的了。
然后數(shù)據(jù)層,我們常用的是Mybatis,易上手,方便維護。但是單表操作比較困難,特別是添加字段或減少字段的時候,比較繁瑣,所以這里我推薦使用Mybatis Plus CRUD 操作,從而節(jié)省大量時間。
作為一個項目骨架,權(quán)限也是我們不能忽略的,Shiro配置簡單,使用也簡單,所以使用Shiro作為我們的的權(quán)限。
考慮到項目可能需要部署多臺,這時候我們的會話等信息需要共享,Redis是現(xiàn)在主流的緩存中間件,也適合我們的項目。
然后因為前后端分離,所以我們使用jwt作為我們用戶身份憑證。
技術(shù)棧:
- SpringBoot
- mybatis plus
- shiro
- lombok
- redis
- hibernate validatior
- jwt
新建Springboot項目
開發(fā)工具與環(huán)境:
- idea
- mysql
- jdk 8
- maven3.3.9
新建好的項目結(jié)構(gòu)如下,SpringBoot版本使用的目前最新的2.2.6.RELEASE版本
pom的jar包導(dǎo)入如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional> </dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional> </dependency>- devtools:項目的熱加載重啟插件
- lombok:簡化代碼的工具
整合mybatis plus
接下來,我們來整合mybatis plus,讓項目能完成基本的增刪改查操作。步驟很簡單:可以去官網(wǎng)看看:
第一步:導(dǎo)入jar包
pom中導(dǎo)入mybatis plus的jar包,因為后面會涉及到代碼生成,所以我們還需要導(dǎo)入頁面模板引擎,這里我們用的是freemarker。
<!--mp--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope> </dependency> <!--mp代碼生成器--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.2.0</version> </dependency>第二步:然后去寫配置文件
# DataSource Config spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456 mybatis-plus:mapper-locations: classpath*:/mapper/**Mapper.xml上面除了配置數(shù)據(jù)庫的信息,還配置了myabtis plus的mapper的xml文件的掃描路徑,這一步不要忘記了。 第三步:開啟mapper接口掃描,添加分頁插件
新建一個包:通過@mapperScan注解指定要變成實現(xiàn)類的接口所在的包,然后包下面的所有接口在編譯之后都會生成相應(yīng)的實現(xiàn)類。PaginationInterceptor是一個分頁插件。
- com.markerhub.config.MybatisPlusConfig
第四步:代碼生成
如果你沒再用其他插件,那么現(xiàn)在就已經(jīng)可以使用mybatis plus了,官方給我們提供了一個代碼生成器,然后我寫上自己的參數(shù)之后,就可以直接根據(jù)數(shù)據(jù)庫表信息生成entity、service、mapper等接口和實現(xiàn)類。
- com.markerhub.CodeGenerator
首先我在數(shù)據(jù)庫中新建了一個user表:
CREATE TABLE `m_user` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`username` varchar(64) DEFAULT NULL,`avatar` varchar(255) DEFAULT NULL,`email` varchar(64) DEFAULT NULL,`password` varchar(64) DEFAULT NULL,`status` int(5) NOT NULL,`created` datetime DEFAULT NULL,`last_login` datetime DEFAULT NULL,PRIMARY KEY (`id`),KEY `UK_USERNAME` (`username`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `m_blog` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`user_id` bigint(20) NOT NULL,`title` varchar(255) NOT NULL,`description` varchar(255) NOT NULL,`content` longtext,`created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,`status` tinyint(4) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4; INSERT INTO `vueblog`.`m_user` (`id`, `username`, `avatar`, `email`, `password`, `status`, `created`, `last_login`) VALUES ('1', 'markerhub', 'https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg', NULL, '96e79218965eb72c92a549dd5a330112', '0', '2020-04-20 10:44:01', NULL); package com.markerhub;import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import java.util.ArrayList; import java.util.List; import java.util.Scanner;// 演示例子,執(zhí)行 main 方法控制臺輸入模塊表名回車自動生成對應(yīng)項目目錄中 public class CodeGenerator {/*** <p>* 讀取控制臺內(nèi)容* </p>*/public static String scanner(String tip) {Scanner scanner = new Scanner(System.in);StringBuilder help = new StringBuilder();help.append("請輸入" + tip + ":");System.out.println(help.toString());if (scanner.hasNext()) {String ipt = scanner.next();if (StringUtils.isNotEmpty(ipt)) {return ipt;}}throw new MybatisPlusException("請輸入正確的" + tip + "!");}public static void main(String[] args) {// 代碼生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java"); // gc.setOutputDir("D:\\test");gc.setAuthor("關(guān)注公眾號:MarkerHub");gc.setOpen(false);// gc.setSwagger2(true); 實體屬性 Swagger2 注解gc.setServiceName("%sService");mpg.setGlobalConfig(gc);// 數(shù)據(jù)源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");// dsc.setSchemaName("public");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setModuleName(null);pc.setParent("com.markerhub");mpg.setPackageInfo(pc);// 自定義配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarkerString templatePath = "/templates/mapper.xml.ftl";// 如果模板引擎是 velocity// String templatePath = "/templates/mapper.xml.vm";// 自定義輸出配置List<FileOutConfig> focList = new ArrayList<>();// 自定義配置會被優(yōu)先輸出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化!!return projectPath + "/src/main/resources/mapper/"+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig = new TemplateConfig();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix("m_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();} }簡潔!方便!經(jīng)過上面的步驟,基本上我們已經(jīng)把mybatis plus框架集成到項目中了。
在UserController中寫個測試:
@RestController @RequestMapping("/user") public class UserController {@AutowiredUserService userService;@GetMapping("/{id}")public Object test(@PathVariable("id") Long id) {return userService.getById(id);} }訪問:http://localhost:8080/user/1 獲得結(jié)果如下,整合成功!
統(tǒng)一結(jié)果封裝
這里我們用到了一個Result的類,這個用于我們的異步統(tǒng)一返回的結(jié)果封裝。一般來說,結(jié)果里面有幾個要素必要的
- 是否成功,可用code表示(如200表示成功,400表示異常)
- 結(jié)果消息
- 結(jié)果數(shù)據(jù)
所以可得到封裝如下:
- com.markerhub.common.lang.Result
整合shiro+jwt,并會話共享
考慮到后面可能需要做集群、負載均衡等,所以就需要會話共享,而shiro的緩存和會話信息,我們一般考慮使用redis來存儲這些數(shù)據(jù),所以,我們不僅僅需要整合shiro,同時也需要整合redis。在開源的項目中,我們找到了一個starter可以快速整合shiro-redis,配置簡單,這里也推薦大家使用。
而因為我們需要做的是前后端分離項目的骨架,所以一般我們會采用token或者jwt(json web token)作為跨域身份驗證解決方案。所以整合shiro的過程中,我們需要引入jwt的身份驗證過程。
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-0VnVTZQF-1610504921265)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210112205243242.png)]
那么我們就開始整合:
我們使用一個shiro-redis-spring-boot-starter的jar包,具體教程可以看官方文檔:github.com/alexxiyang/…
第一步:導(dǎo)入shiro-redis的starter包:還有jwt的工具包,以及為了簡化開發(fā),我引入了hutool工具包。
<dependency><groupId>org.crazycake</groupId><artifactId>shiro-redis-spring-boot-starter</artifactId><version>3.2.1</version> </dependency> <!-- hutool工具類--> <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.3</version> </dependency> <!-- jwt --> <dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version> </dependency>第二步:編寫配置:
ShiroConfig
- com.markerhub.config.ShiroConfig
上面ShiroConfig,我們主要做了幾件事情:
那么,接下來,我們聊聊ShiroConfig中出現(xiàn)的AccountRealm,還有JwtFilter。
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-KSaMftFI-1610504921268)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210112214806324.png)]
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-MXjXNgV9-1610504921270)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210112215020809.png)]
AccountRealm
AccountRealm是shiro進行登錄或者權(quán)限校驗的邏輯所在,算是核心了,我們需要重寫3個方法,分別是
- supports:為了讓realm支持jwt的憑證校驗
- doGetAuthorizationInfo:權(quán)限校驗
- doGetAuthenticationInfo:登錄認證校驗
我們先來總體看看AccountRealm的代碼,然后逐個分析:
- com.markerhub.shiro.AccountRealm
其實主要就是doGetAuthenticationInfo登錄認證這個方法,可以看到我們通過jwt獲取到用戶信息,判斷用戶的狀態(tài),最后異常就拋出對應(yīng)的異常信息,否者封裝成SimpleAuthenticationInfo返回給shiro。 接下來我們逐步分析里面出現(xiàn)的新類:
1、shiro默認supports的是UsernamePasswordToken,而我們現(xiàn)在采用了jwt的方式,所以這里我們自定義一個JwtToken,來完成shiro的supports方法。
JwtToken
- com.markerhub.shiro.JwtToken
2、JwtUtils是個生成和校驗jwt的工具類,其中有些jwt相關(guān)的密鑰信息是從項目配置文件中配置的:
@Component @ConfigurationProperties(prefix = "markerhub.jwt") public class JwtUtils {private String secret;private long expire;private String header;/*** 生成jwt token*/public String generateToken(long userId) {...}// 獲取jwt的信息public Claims getClaimByToken(String token) {...}/*** token是否過期* @return true:過期*/public boolean isTokenExpired(Date expiration) {return expiration.before(new Date());} }3、而在AccountRealm我們還用到了AccountProfile,這是為了登錄成功之后返回的一個用戶信息的載體,
AccountProfile
- com.markerhub.shiro.AccountProfile
第三步,ok,基本的校驗的路線完成之后,我們需要少量的基本信息配置:
shiro-redis:enabled: trueredis-manager:host: 127.0.0.1:6379 markerhub:jwt:# 加密秘鑰secret: f4e2e52034348f86b67cde581c0f9eb5# token有效時長,7天,單位秒expire: 604800header: token第四步:另外,如果你項目有使用spring-boot-devtools,需要添加一個配置文件,在resources目錄下新建文件夾META-INF,然后新建文件spring-devtools.properties,這樣熱重啟時候才不會報錯。
- resources/META-INF/spring-devtools.properties
JwtFilter
第五步:定義jwt的過濾器JwtFilter。
這個過濾器是我們的重點,這里我們繼承的是Shiro內(nèi)置的AuthenticatingFilter,一個可以內(nèi)置了可以自動登錄方法的的過濾器,有些同學(xué)繼承BasicHttpAuthenticationFilter也是可以的。
我們需要重寫幾個方法:
createToken:實現(xiàn)登錄,我們需要生成我們自定義支持的JwtToken
onAccessDenied:攔截校驗,當頭部沒有Authorization時候,我們直接通過,不需要自動登錄;當帶有的時候,首先我們校驗jwt的有效性,沒問題我們就直接執(zhí)行executeLogin方法實現(xiàn)自動登錄
onLoginFailure:登錄異常時候進入的方法,我們直接把異常信息封裝然后拋出
preHandle:攔截器的前置攔截,因為我們是前后端分析項目,項目中除了需要跨域全局配置之外,我們再攔截器中也需要提供跨域支持。這樣,攔截器才不會在進入Controller之前就被限制了。
跨域
下面我們看看總體的代碼:
- com.markerhub.shiro.JwtFilter
那么到這里,我們的shiro就已經(jīng)完成整合進來了,并且使用了jwt進行身份校驗。
異常處理
有時候不可避免服務(wù)器報錯的情況,如果不配置異常處理機制,就會默認返回tomcat或者nginx的5XX頁面,對普通用戶來說,不太友好,用戶也不懂什么情況。這時候需要我們程序員設(shè)計返回一個友好簡單的格式給前端。
處理辦法如下:通過使用@ControllerAdvice來進行統(tǒng)一異常處理,@ExceptionHandler(value = RuntimeException.class)來指定捕獲的Exception各個類型異常 ,這個異常的處理,是全局的,所有類似的異常,都會跑到這個地方處理。
- com.markerhub.common.exception.GlobalExceptionHandler
步驟二、定義全局異常處理,@ControllerAdvice表示定義全局控制器異常處理,@ExceptionHandler表示針對性異常處理,可對每種異常針對性處理。
/*** 全局異常處理*/ @Slf4j @RestControllerAdvice public class GlobalExcepitonHandler {// 捕捉shiro的異常@ResponseStatus(HttpStatus.UNAUTHORIZED)@ExceptionHandler(ShiroException.class)public Result handle401(ShiroException e) {return Result.fail(401, e.getMessage(), null);}/*** 處理Assert的異常*/@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(value = IllegalArgumentException.class)public Result handler(IllegalArgumentException e) throws IOException {log.error("Assert異常:-------------->{}",e.getMessage());return Result.fail(e.getMessage());}/*** @Validated 校驗錯誤異常處理*/@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(value = MethodArgumentNotValidException.class)public Result handler(MethodArgumentNotValidException e) throws IOException {log.error("運行時異常:-------------->",e);BindingResult bindingResult = e.getBindingResult();ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();return Result.fail(objectError.getDefaultMessage());}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(value = RuntimeException.class)public Result handler(RuntimeException e) throws IOException {log.error("運行時異常:-------------->",e);return Result.fail(e.getMessage());} }上面我們捕捉了幾個異常:
- ShiroException:shiro拋出的異常,比如沒有權(quán)限,用戶登錄異常
- IllegalArgumentException:處理Assert的異常
- MethodArgumentNotValidException:處理實體校驗的異常
- RuntimeException:捕捉其他異常
實體校驗
當我們表單數(shù)據(jù)提交的時候,前端的校驗我們可以使用一些類似于jQuery Validate等js插件實現(xiàn),而后端我們可以使用Hibernate validatior來做校驗。
我們使用springboot框架作為基礎(chǔ),那么就已經(jīng)自動集成了Hibernate validatior。
第一步:首先在實體的屬性上添加對應(yīng)的校驗規(guī)則,比如:
@TableName("m_user") public class User implements Serializable {private static final long serialVersionUID = 1L;@TableId(value = "id", type = IdType.AUTO)private Long id;@NotBlank(message = "昵稱不能為空")private String username;@NotBlank(message = "郵箱不能為空")@Email(message = "郵箱格式不正確")private String email;... }第二步 :這里我們使用@Validated注解方式,如果實體不符合要求,系統(tǒng)會拋出異常,那么我們的異常處理中就捕獲到MethodArgumentNotValidException。
- com.markerhub.controller.UserController
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-0XLQafDP-1610504921275)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210112233105770.png)]
跨域問題
因為是前后端分析,所以跨域問題是避免不了的,我們直接在后臺進行全局跨域處理:
- com.markerhub.config.CorsConfig
jwt對跨域的支持(JwtFilter中)
/*** 對跨域提供支持*/ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {HttpServletRequest httpServletRequest = WebUtils.toHttp(request);HttpServletResponse httpServletResponse = WebUtils.toHttp(response);httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));// 跨域時會首先發(fā)送一個OPTIONS請求,這里我們給OPTIONS請求直接返回正常狀態(tài)if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());return false;}return super.preHandle(request, response); }ok,因為我們系統(tǒng)開發(fā)的接口比較簡單,所以我就不集成swagger2啦,也比較簡單而已。下面我們就直接進入我們的正題,進行編寫登錄接口。
登錄接口開發(fā)
登錄的邏輯其實很簡答,只需要接受賬號密碼,然后把用戶的id生成jwt,返回給前段,為了后續(xù)的jwt的延期,所以我們把jwt放在header上。具體代碼如下:
- com.markerhub.controller.AccountController
接口測試
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Emum2aFu-1610504921276)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210113002623802.png)]
博客接口開發(fā)
我們的骨架已經(jīng)完成,接下來,我們就可以添加我們的業(yè)務(wù)接口了,下面我以一個簡單的博客列表、博客詳情頁為例子開發(fā):
- com.markerhub.controller.BlogController
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-2rqZ3xqN-1610504921278)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210113094625149.png)]
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-J9reyYof-1610504921281)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210113101753882.png)]
json格式
數(shù)字不加雙引號
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-UDyRsnPw-1610504921282)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210113102351294.png)]
注意@RequiresAuthentication說明需要登錄之后才能訪問的接口,其他需要權(quán)限的接口可以添加shiro的相關(guān)注解。 接口比較簡單,我們就不多說了,基本增刪改查而已。注意的是edit方法是需要登錄才能操作的受限資源。
接口測試
總結(jié)
以上是生活随笔為你收集整理的SpringBoot+Vue博客系统---后端接口开发的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蜘蛛带什么天赋(蜘蛛出装天赋)
- 下一篇: vue的基本项目结构