├── src ├── main │ ├── resources │ │ ├── application-test.yml │ │ ├── application-prod.yml │ │ ├── application.yml │ │ ├── application-dev.yml │ │ ├── mapper │ │ │ └── UserMapper.xml │ │ └── banner.txt │ └── java │ │ └── com │ │ └── company │ │ └── project │ │ ├── dao │ │ └── UserMapper.java │ │ ├── service │ │ ├── IUserService.java │ │ └── impl │ │ │ └── UserServiceImpl.java │ │ ├── core │ │ ├── ServiceException.java │ │ ├── ResultCode.java │ │ ├── ResultGenerator.java │ │ ├── ApplicationContextUtil.java │ │ └── Result.java │ │ ├── configurer │ │ ├── MyBatisPlusConfig.java │ │ ├── SwaggerConfiguration.java │ │ ├── LoginInterceptor.java │ │ └── WebMvcConfigurer.java │ │ ├── utils │ │ ├── MD5Utils.java │ │ └── JwtUtils.java │ │ ├── model │ │ └── User.java │ │ ├── Application.java │ │ └── web │ │ └── UserController.java └── test │ ├── java │ ├── com │ │ └── company │ │ │ └── project │ │ │ └── Tester.java │ └── CodeGenerator.java │ └── resources │ ├── user.sql │ └── templates │ └── controller.java.ftl ├── .gitignore ├── README.md └── pom.xml /src/main/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | # 测试环境配置 2 | -------------------------------------------------------------------------------- /src/main/resources/application-prod.yml: -------------------------------------------------------------------------------- 1 | # 生产环境配置 2 | knife4j: 3 | production: true #生成环境禁用查看接口文档 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | 3 | ### STS ### 4 | .apt_generated 5 | .classpath 6 | .factorypath 7 | .project 8 | .settings 9 | .springBeans 10 | 11 | ### IntelliJ IDEA ### 12 | .idea 13 | *.iws 14 | *.iml 15 | *.ipr 16 | 17 | ### NetBeans ### 18 | nbproject/private/ 19 | build/ 20 | nbbuild/ 21 | dist/ 22 | nbdist/ 23 | .nb-gradle/ -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: dev 4 | mvc: 5 | throw-exception-if-no-handler-found: true 6 | resources: 7 | add-mappings: false 8 | application: 9 | name: Springboot-api 10 | jackson: 11 | date-format: yyyy-MM-dd HH:mm:ss 12 | time-zone: GMT+8 13 | server: 14 | port: 8080 15 | -------------------------------------------------------------------------------- /src/main/java/com/company/project/dao/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.company.project.dao; 2 | 3 | import com.company.project.model.User; 4 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 5 | 6 | /** 7 | *
8 | * Mapper 接口 9 | *
10 | * 11 | * @author project 12 | * @since 2020-01-08 13 | */ 14 | public interface UserMapper extends BaseMapper8 | * 服务类 9 | *
10 | * 11 | * @author project 12 | * @since 2020-01-08 13 | */ 14 | public interface IUserService extends IService11 | * 服务实现类 12 | *
13 | * 14 | * @author project 15 | * @since 2020-01-08 16 | */ 17 | @Service 18 | public class UserServiceImpl extends ServiceImpl18 | * 19 | *
20 | * 21 | * @author project 22 | * @since 2020-01-08 23 | */ 24 | @Data 25 | @EqualsAndHashCode(callSuper = false) 26 | @Accessors(chain = true) 27 | public class User implements Serializable { 28 | 29 | private static final long serialVersionUID = 1L; 30 | 31 | /** 32 | * 主键 33 | */ 34 | @TableId(value = "id", type = IdType.AUTO) 35 | private Integer id; 36 | 37 | /** 38 | * 用户名 39 | */ 40 | @NotEmpty(message = "用户名不能为空!") 41 | private String username; 42 | 43 | /** 44 | * 密码 45 | */ 46 | @NotEmpty(message = "密码不能为空!") 47 | private String password; 48 | 49 | /** 50 | * 昵称 51 | */ 52 | private String nickName; 53 | 54 | /** 55 | * 性别 56 | */ 57 | private Integer sex; 58 | 59 | /** 60 | * 创建时间 61 | */ 62 | private Date createDate; 63 | 64 | /** 65 | * 创建人 66 | */ 67 | private Integer createUser; 68 | 69 | /** 70 | * 修改时间 71 | */ 72 | private Date updateDate; 73 | 74 | /** 75 | * 修改人 76 | */ 77 | private Integer updateUser; 78 | 79 | /** 80 | * 删除标志0未删 1删除 81 | */ 82 | @TableLogic 83 | private Integer delFlag; 84 | 85 | /** 86 | * 登陆返回token 87 | */ 88 | @TableField(exist = false) 89 | private String token; 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/company/project/Application.java: -------------------------------------------------------------------------------- 1 | package com.company.project; 2 | 3 | import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; 4 | import org.mybatis.spring.annotation.MapperScan; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.ConfigurableApplicationContext; 10 | import org.springframework.core.env.Environment; 11 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 12 | 13 | import java.net.InetAddress; 14 | 15 | @SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) 16 | @MapperScan("com.company.project.dao") 17 | public class Application { 18 | 19 | private static Logger logger= LoggerFactory.getLogger(Application.class); 20 | 21 | public static void main(String[] args) throws Exception { 22 | 23 | ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); 24 | 25 | Environment env = application.getEnvironment(); 26 | logger.info("\n----------------------------------------------------------\n\t" + 27 | "Application '{}' is running! Access URLs:\n\t" + 28 | "Local: \t\thttp://localhost:{}\n\t" + 29 | "External: \thttp://{}:{}\n\t" + 30 | "Doc: \thttp://{}:{}/doc.html\n" + 31 | "----------------------------------------------------------", 32 | env.getProperty("spring.application.name"), 33 | env.getProperty("server.port"), 34 | InetAddress.getLocalHost().getHostAddress(), 35 | env.getProperty("server.port"), 36 | InetAddress.getLocalHost().getHostAddress(), 37 | env.getProperty("server.port")); 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /src/main/java/com/company/project/utils/JwtUtils.java: -------------------------------------------------------------------------------- 1 | package com.company.project.utils; 2 | 3 | import com.company.project.model.User; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.Jwts; 6 | import io.jsonwebtoken.SignatureAlgorithm; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.util.Date; 10 | 11 | /** 12 | * jwt工具类 13 | */ 14 | public class JwtUtils { 15 | 16 | public static final String USER_ID_KEY = "user_id_key"; 17 | 18 | public static final String USER_ACCOUNT_KEY = "user_account_key"; 19 | 20 | 21 | public static final String SUBJECT = "onehee"; 22 | 23 | public static final long EXPIRE = 1000*60*60*24*7; //过期时间,毫秒,一周 24 | 25 | //秘钥 26 | public static final String APPSECRET = "onehee666"; 27 | 28 | /** 29 | * 生成jwt 30 | * @param user 31 | * @return 32 | */ 33 | public static String geneJsonWebToken(User user){ 34 | 35 | String token = Jwts.builder().setSubject(SUBJECT) 36 | .claim("id",user.getId()) 37 | .claim("userName",user.getUsername()) 38 | .setIssuedAt(new Date()) 39 | .setExpiration(new Date(System.currentTimeMillis()+EXPIRE)) 40 | .signWith(SignatureAlgorithm.HS256,APPSECRET).compact(); 41 | 42 | return token; 43 | } 44 | 45 | 46 | /** 47 | * 校验token 48 | * @param token 49 | * @return 50 | */ 51 | public static Claims checkJWT(String token ){ 52 | 53 | try{ 54 | final Claims claims = Jwts.parser().setSigningKey(APPSECRET). 55 | parseClaimsJws(token).getBody(); 56 | return claims; 57 | 58 | }catch (Exception e){ } 59 | return null; 60 | 61 | } 62 | 63 | 64 | /** 65 | * 判断当前登陆用户是不是admin 66 | * @param request 67 | * @return 68 | */ 69 | public static boolean isAdmin(HttpServletRequest request) { 70 | if (request.getAttribute(USER_ACCOUNT_KEY) == null) { 71 | return false; 72 | } 73 | if ("admin".equals(request.getAttribute(USER_ACCOUNT_KEY).toString())){ 74 | return true; 75 | } else { 76 | return false; 77 | } 78 | } 79 | 80 | 81 | 82 | } -------------------------------------------------------------------------------- /src/main/java/com/company/project/configurer/LoginInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.company.project.configurer; 2 | 3 | 4 | import com.alibaba.fastjson.JSON; 5 | import com.company.project.core.Result; 6 | import com.company.project.core.ResultCode; 7 | import com.company.project.utils.JwtUtils; 8 | import io.jsonwebtoken.Claims; 9 | import org.apache.commons.lang3.StringUtils; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | 17 | import java.io.IOException; 18 | 19 | import static com.company.project.utils.JwtUtils.USER_ACCOUNT_KEY; 20 | import static com.company.project.utils.JwtUtils.USER_ID_KEY; 21 | 22 | /** 23 | *登陆拦截器 24 | */ 25 | public class LoginInterceptor extends HandlerInterceptorAdapter { 26 | 27 | private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); 28 | @Override 29 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 30 | //拦截接口 31 | //从header中获取token 32 | String token = request.getHeader("token"); 33 | //如果header中不存在token,则从参数中获取token 34 | if(StringUtils.isBlank(token)){ 35 | token = request.getParameter("token"); 36 | } 37 | //token为空返回 38 | if(StringUtils.isBlank(token)){ 39 | Result result = new Result(); 40 | result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); 41 | responseResult(response, result); 42 | return false; 43 | }// 校验并解析token,如果token过期或者篡改,则会返回null 44 | Claims claims = JwtUtils.checkJWT(token); 45 | if(null == claims){ 46 | Result result = new Result(); 47 | result.setCode(ResultCode.UNAUTHORIZED).setMessage("登陆失效, 请重新登陆").setSuccess(false); 48 | responseResult(response, result); 49 | return false; 50 | } 51 | // 校验通过后,设置用户信息到request里,在Controller中从Request域中获取用户信息 52 | request.setAttribute(USER_ID_KEY, claims.get("id")); 53 | request.setAttribute(USER_ACCOUNT_KEY, claims.get("account")); 54 | return true; 55 | } 56 | 57 | 58 | 59 | private void responseResult(HttpServletResponse response, Result result) { 60 | response.setCharacterEncoding("UTF-8"); 61 | response.setHeader("Content-type", "application/json;charset=UTF-8"); 62 | response.setStatus(200); 63 | try { 64 | response.getWriter().write(JSON.toJSONString(result)); 65 | } catch (IOException ex) { 66 | logger.error(ex.getMessage()); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/test/resources/user.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat Premium Data Transfer 3 | 4 | Source Server : localhost 5 | Source Server Type : MySQL 6 | Source Server Version : 50529 7 | Source Host : localhost:3306 8 | Source Schema : project 9 | 10 | Target Server Type : MySQL 11 | Target Server Version : 50529 12 | File Encoding : 65001 13 | 14 | Date: 08/01/2020 15:53:02 15 | */ 16 | 17 | SET NAMES utf8mb4; 18 | SET FOREIGN_KEY_CHECKS = 0; 19 | 20 | -- ---------------------------- 21 | -- Table structure for user 22 | -- ---------------------------- 23 | DROP TABLE IF EXISTS `user`; 24 | CREATE TABLE `user` ( 25 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', 26 | `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', 27 | `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', 28 | `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', 29 | `sex` int(1) NULL DEFAULT NULL COMMENT '性别', 30 | `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', 31 | `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', 32 | `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', 33 | `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', 34 | `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', 35 | PRIMARY KEY (`id`) USING BTREE 36 | ) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; 37 | 38 | -- ---------------------------- 39 | -- Records of user 40 | -- ---------------------------- 41 | INSERT INTO `user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '土豆', 1, NULL, NULL, NULL, NULL, 0); 42 | INSERT INTO `user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-2', 1, NULL, NULL, NULL, NULL, 0); 43 | INSERT INTO `user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-3', 1, NULL, NULL, NULL, NULL, 0); 44 | INSERT INTO `user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-4', 1, NULL, NULL, NULL, NULL, 0); 45 | INSERT INTO `user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-5', 1, NULL, NULL, NULL, NULL, 0); 46 | INSERT INTO `user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-6', 1, NULL, NULL, NULL, NULL, 0); 47 | INSERT INTO `user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-7', 1, NULL, NULL, NULL, NULL, 0); 48 | INSERT INTO `user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-8', 1, NULL, NULL, NULL, NULL, 0); 49 | INSERT INTO `user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-9', 1, NULL, NULL, NULL, NULL, 0); 50 | INSERT INTO `user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-10', 1, NULL, NULL, NULL, NULL, 0); 51 | 52 | SET FOREIGN_KEY_CHECKS = 1; 53 | -------------------------------------------------------------------------------- /src/test/resources/templates/controller.java.ftl: -------------------------------------------------------------------------------- 1 | package ${package.Controller}; 2 | 3 | import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 4 | import com.company.project.core.Result; 5 | import com.company.project.core.ResultGenerator; 6 | import io.swagger.annotations.ApiImplicitParam; 7 | import io.swagger.annotations.ApiImplicitParams; 8 | import org.springframework.web.bind.annotation.*; 9 | import ${package.Service}.${table.serviceName}; 10 | import ${package.Entity}.${entity}; 11 | import io.swagger.annotations.Api; 12 | import io.swagger.annotations.ApiOperation; 13 | import lombok.extern.slf4j.Slf4j; 14 | import com.baomidou.mybatisplus.core.metadata.IPage; 15 | 16 | import javax.annotation.Resource; 17 | <#if restControllerStyle> 18 | import org.springframework.web.bind.annotation.RestController; 19 | <#else> 20 | import org.springframework.stereotype.Controller; 21 | #if> 22 | <#if superControllerClassPackage??> 23 | import ${superControllerClassPackage}; 24 | #if> 25 | 26 | /** 27 | *
28 | * ${table.comment!} 前端控制器 29 | *
30 | * 31 | * @author ${author} 32 | * @since ${date} 33 | */ 34 | <#if restControllerStyle> 35 | @Api(tags = {"${table.comment!}"}) 36 | @Slf4j 37 | @RestController 38 | <#else> 39 | @Controller 40 | #if> 41 | @RequestMapping("<#if package.ModuleName??>/${package.ModuleName}#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}#if>") 42 | <#if kotlin> 43 | class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}()#if> 44 | <#else> 45 | <#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ 46 | <#else>public class ${table.controllerName} { 47 | #if> 48 | 49 | @Resource 50 | private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; 51 | 52 | 53 | @ApiOperation(value = "新增${table.comment!}") 54 | @PostMapping("add") 55 | public Result add(@RequestBody ${entity} ${entity?uncap_first}){ 56 | ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); 57 | return ResultGenerator.genSuccessResult(); 58 | } 59 | 60 | @ApiOperation(value = "删除${table.comment!}") 61 | @PostMapping("delete/{id}") 62 | public Result delete(@PathVariable("id") Long id){ 63 | ${(table.serviceName?substring(1))?uncap_first}.removeById(id); 64 | return ResultGenerator.genSuccessResult(); 65 | } 66 | 67 | @ApiOperation(value = "更新${table.comment!}") 68 | @PostMapping("update") 69 | public Result update(@RequestBody ${entity} ${entity?uncap_first}){ 70 | ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); 71 | return ResultGenerator.genSuccessResult(); 72 | } 73 | 74 | @ApiOperation(value = "查询${table.comment!}分页数据") 75 | @ApiImplicitParams({ 76 | @ApiImplicitParam(name = "currentPage", value = "页码"), 77 | @ApiImplicitParam(name = "pageCount", value = "每页条数") 78 | }) 79 | @GetMapping("listByPage") 80 | public Result findListByPage(@RequestParam Integer currentPage, 81 | @RequestParam Integer pageCount){ 82 | Page page = new Page(currentPage, pageCount); 83 | IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); 84 | return ResultGenerator.genSuccessResult(iPage); 85 | } 86 | 87 | @ApiOperation(value = "id查询${table.comment!}") 88 | @GetMapping("getById/{id}") 89 | public Result findById(@PathVariable Long id){ 90 | return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); 91 | } 92 | 93 | } 94 | #if> -------------------------------------------------------------------------------- /src/main/java/com/company/project/web/UserController.java: -------------------------------------------------------------------------------- 1 | package com.company.project.web; 2 | 3 | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; 4 | import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 5 | import com.company.project.core.Result; 6 | import com.company.project.core.ResultGenerator; 7 | import com.company.project.utils.JwtUtils; 8 | import com.company.project.utils.MD5Utils; 9 | import io.swagger.annotations.ApiImplicitParam; 10 | import io.swagger.annotations.ApiImplicitParams; 11 | import org.springframework.web.bind.annotation.*; 12 | import com.company.project.service.IUserService; 13 | import com.company.project.model.User; 14 | import io.swagger.annotations.Api; 15 | import io.swagger.annotations.ApiOperation; 16 | import lombok.extern.slf4j.Slf4j; 17 | import com.baomidou.mybatisplus.core.metadata.IPage; 18 | 19 | import javax.annotation.Resource; 20 | import javax.validation.Valid; 21 | 22 | import org.springframework.web.bind.annotation.RestController; 23 | 24 | /** 25 | *26 | * 前端控制器 27 | *
28 | * 29 | * @author project 30 | * @since 2020-01-08 31 | */ 32 | @Slf4j 33 | @RestController 34 | @RequestMapping("/api/user") 35 | public class UserController { 36 | 37 | @Resource 38 | private IUserService userService; 39 | 40 | @ApiOperation("登陆") 41 | @PostMapping("/login") 42 | public Result login(@RequestBody @Valid User user) { 43 | QueryWrapper