1.Java后端接口开发
1.1初始环境配置
??新建springboot项目 ??选择相应的依赖 ??删除不必要文件和更改Pom.xml内容 ??整合mybatis plus ??导入jar包
<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>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
??写配置文件.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: admin
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
??新建MybatisPlusConfig配置
@Configuration
@EnableTransactionManagement
@MapperScan("com.markerhub.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
??使用MybatisPlus的CodeGeneator插件根据配置的数据库自动生成接口和类,这里要重新在CodeGeneator里进行配置数据库。 ??CodeGeneator.java代码如下:
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;
public class CodeGenerator {
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.setAuthor("关注公众号:MarkerHub");
gc.setOpen(false);
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent("com.markerhub");
mpg.setPackageInfo(pc);
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
String templatePath = "/templates/mapper.xml.ftl";
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
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();
}
}
??数据库代码:
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 AUTO_INCREMENT=2 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,
`desription` 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;
??最后得到以下架构:
1.2用户业务
??新建Result类进行最终传递给前端的结果展示。
package com.markerhub.common.lang;
import lombok.Data;
import java.io.Serializable;
@Data
public class Result implements Serializable {
private int code;
private String msg;
private Object data;
public static Result succ(Object data){
return succ(200,"操作成功",data);
}
public static Result succ(int code,String msg,Object data){
Result r = new Result();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
return r;
}
public static Result fail(String msg,Object data){
return fail(400,msg,null);
}
public static Result fail(int code,String msg,Object data){
Result r = new Result();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
return r;
}
}
??写用户操作接口
package com.markerhub.controller;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/index")
public Object index(){
User user = userService.getById(2L);
return Result.succ(user);
}
}
??配置完成后运行springboot application,输入spingboot的默认8080端口
http://localhost:8080/user/index
??可以看到读取到了数据库里的数据,同时返回了给前端可以获取的code和message。 ??JSON展示插件可以下载JSONVIEW,谷歌插件商店里下载。
1.3 shiro整合jwt逻辑
??后面需要做集群、负载均衡,因此用到会话共享,采用redis存储shiro的缓存和会话信息。开源项目shiro-redis整合了这两个模块。 整合第一步: 导入jar包
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis-spring-boot-starter</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
|