赞
踩
springboot是所有基于spring开发项目的起点。springboot的设计是为了尽可能快的启动spring应用程序,并且尽可能的减少配置文件。约定优于配置,一种软件设计范式。
spring是javaEE的轻量化替代品,同时通过依赖注入和面向切面编程,使其功能强大;不过它的组件代码虽然是轻量化的,但是它的配置文件却是重量级的。尽管在后续的更新开发中,通过引入基于注解的组件扫描、基于java的可重构配置,一定程度上降低了程度;不过项目的依赖管理也还是一种耗时耗力的事情。
springboot对于spring的问题进行了改善和优化,同时基于约定优于配置的思想,可以使得开发人员不必在配置和逻辑业务中进行思维的转换,全身心投入逻辑业务的代码编写中,从而大大提高开发效率,一定程度上缩短了项目周期。
vue是一个构建数据驱动的web界面的渐进式框架。
vue的目标是通过尽可能简单的API实现响应的数据绑定和组合视图组件。易于上手,同时易于与第三方库或既有项目的整合。
vue专注于MVVM的view层;它的核心是MVVM中的VM,即ViewModel,负责连接view和model,保证视图与数据的一致性,这种轻量化的架构让前端开发更加高效、便捷。
开发一个项目,选择更加高校、便捷而且轻量化配置的框架,能够使得开发过程中减少除业务逻辑的代码开发外的所有时间,使得开发人员能够只用专注于代码开发,能够使得开发过程十分高效。
idea作为一款业界评价甚高的开发工具,具有十分强大的功能,包括智能代码助手、代码自动提示、重构、javaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析等等,同时,用户体验不够良好的eclipse、集成度不高的Vim、不够稳定的VS Code,开发者更愿意偏向使用idea作为开发工具。
Mysql是一个关系型数据库管理系统。由于其的简单易用、价格低(对于多数个人用户而言是免费的)、小巧、支持查询语言(支持Sql)、性能高校、连接稳定、安全可靠、可移植性、开放式的分发、运行速度快。
简单易学,容易上手;较JDBC代码量少;并不需要手动开关连接;很好的与各种数据库兼容;提供了很多第三方插件;同时能够与spring有很好的集成;想当灵活。sql语句编写在xml文件中,与程度代码分离,减少耦合,便于管理和优化,易与重用;能够利用xml文件更好的编写动态sql语句;提供映射标签,支持关系映射。
sql语句编写工作量大、sql语句依赖于数据库,移植性差。
简单来说就是一款Mybatis的增强工具,用于简化开发、提高效率。它并不需要编写sql语句、配置xml文件,只需要创捷查询类,就能够迅速连接数据库。也正因此,将service层、dao层、entity层绑定一起,耦合度太高。
填写名称、设定项目路径、选择JDK、点击下一步;
选择springboot的版本(建议3.0以下)、选择是否下载JDK以及Maven库、选择所需的依赖项目(勾选web->spring web)(其余依赖后续通过maven快速配置)、点击创建;
- <?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.12</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
-
- <groupId>com.example</groupId>
- <artifactId>System</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>System</name>
- <description>System</description>
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>11</java.version>
- <mybatis-plus.version>3.2.0</mybatis-plus.version>
- </properties>
-
- <dependencies>
- <!-- 添加springmvc依赖 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <!-- Mybatis -->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.4</version>
- </dependency>
-
- <!-- Mybatis-plus -->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>${mybatis-plus.version}</version>
- </dependency>
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-generator</artifactId>
- <version>${mybatis-plus.version}</version>
- </dependency>
-
- <!-- websocket -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
-
- <!-- 数据库连接池 druid -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.2.2</version>
- </dependency>
-
- <!-- mysql -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.30</version>
- </dependency>
-
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.5.4</version>
- </dependency>
-
- <!-- excel导出 -->
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>4.1.2</version>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
-
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>2.9.2</version>
- </dependency>
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>2.9.2</version>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>2.7.12</version>
- <configuration>
- <fork>true</fork>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <repositories>
- <repository>
- <id>public</id>
- <name>aliyun nexus</name>
- <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
- <releases>
- <enabled>true</enabled>
- </releases>
- </repository>
- </repositories>
-
- <pluginRepositories>
- <pluginRepository>
- <id>public</id>
- <name>aliyun nexus</name>
- <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
- <releases>
- <enabled>true</enabled>
- </releases>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </pluginRepository>
- </pluginRepositories>
- </project>
- # 服务器端口设置
- server:
- port: 9999
- spring:
- # 数据库连接
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- username: root
- password: 123456
- url: jdbc:mysql://localhost:3306/workdatabase?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8
- type: com.alibaba.druid.pool.DruidDataSource
- # 网络服务
- servlet:
- multipart:
- max-file-size: 100MB
- max-request-size: 100MB
-
- # mybatis配置
- mybatis:
- mapper-locations: classpath:mapper/*.xml
-
- logging:
- level:
- com:
- example:
- mapper:
- debug
项目路径common.handle下,新建类,实现list转换string的类型转换。
- package com.example.system.common.handle;
-
- import cn.hutool.json.JSONUtil;
- import org.apache.ibatis.type.BaseTypeHandler;
- import org.apache.ibatis.type.JdbcType;
-
- import java.sql.CallableStatement;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
-
- /**
- * list转换string
- */
- public class ListHandler extends BaseTypeHandler<List> {
-
- @Override
- public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
- preparedStatement.setObject(i, JSONUtil.toJsonStr(list));
- }
-
- @Override
- public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
- return JSONUtil.parseArray(resultSet.getString(s));
- }
-
- @Override
- public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
- return JSONUtil.parseArray(resultSet.getString(i));
- }
-
- @Override
- public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
- return JSONUtil.parseArray(callableStatement.getString(i));
- }
- }
结果信息处理类,实现对各类处理信息的响应。
- package com.example.system.common.handle;
-
- /**
- * 处理结果
- * @param <T>
- */
- public class Result<T> {
- private String code; // 状态码
- private String msg; // 信息
- private T data; // 数据
-
- public String getCode() {
- return code;
- }
-
- public void setCode(String code) {
- this.code = code;
- }
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
- public T getData() {
- return data;
- }
-
- public void setData(T data) {
- this.data = data;
- }
-
- public Result() {
- }
-
- public Result(T data) {
- this.data = data;
- }
-
- // 结果成功
- public static Result success() {
- Result result = new Result<>();
- result.setCode("0");
- result.setMsg("成功");
- return result;
- }
-
- public static <T> Result<T> success(T data) {
- Result<T> result = new Result<>(data);
- result.setCode("0");
- result.setMsg("成功");
- return result;
- }
-
- // 结果失败
- public static Result error(String code, String msg) {
- Result result = new Result();
- result.setCode(code);
- result.setMsg(msg);
- return result;
- }
- }
作为一个管理系统,首先得要有用户(基础属性),无论是管理员(权限属性),还是普通用户,在访问系统时都是一名用户。
而用户所具备的属性应该有:用户登录账号(用户名、密码)、用户使用系统时个性化(昵称、头像)、用户的个人信息(邮箱、手机号码、地址、年龄)。
同时对于权限属性应该有:权限、许可(对于权限属性分析具备两个属性,需求分析见权限类)。
基于此,实体类User的创建:
a.数据库表主键:数据库对应的id;
b.基础属性:用户名username、用户密码password、用户昵称nickName、用户邮箱email、用户手机号码phone、用户头像avatar、用户地址address、用户年龄age;
c.权限属性:权限role、许可premission。
- package com.example.system.entity;
-
- 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 com.baomidou.mybatisplus.extension.activerecord.Model;
- import com.example.system.common.handle.ListHandler;
- import lombok.Data;
-
- import java.util.List;
-
- /**
- * 用户:访问系统需要具备一个的身份
- */
-
- @Data
- @TableName(value = "user", autoResultMap = true)
- public class User extends Model<User> {
-
- /**
- * 主键
- */
- @TableId(value = "id", type = IdType.AUTO)
- private long id;
-
- private String username;
- private String password;
- private String nickName;
- private String email;
- private String phone;
- private String avatar;
- private String address;
- private Integer age;
-
- // 设置权限
- @TableField(typeHandler = ListHandler.class)
- private List<Long> role;
-
- @TableField(exist = false)
- private List<Permission> permission;
-
- }
不同用户访问系统,所能够访问的功能应有所不同,因此需要给用户添加权限设置;系统功能可添加删除,具备多样性,可面向不同用户,因此权限类不是指用户具有的访问不同功能的权限,而是一个权限角色;对于许多的功能,为了完成不同用户访问功能时的限制,给予不同功能设置许可;而对于权限角色,则是不同权限角色具备一定的功能许可;为角色添加限制时,是为角色绑定上权限角色,从而获取所绑定的权限角色所具有的许可,以此具备访问功能的权限。
a.数据库表主键:数据库对应的id;
b.权限角色的名字:name;
c.对权限角色的描述:description;
d.具有的功能许可:permission。
- package com.example.system.entity;
-
- 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 com.baomidou.mybatisplus.extension.activerecord.Model;
- import com.example.system.common.handle.ListHandler;
- import lombok.Data;
-
- import java.util.List;
-
- /**
- * 权限角色:用户访问系统内部不同功能。需要具备不同权限,设置不同的权限角色,具备不同功能所需要的许可;
- * <p>具体解释</p>
- * 访问功能 ----> 需要权限 ----> 权限角色具备一定的许可 ---->
- * 用户被设定为权限角色 ----> 用户具备权限角色所具备的权限许可 ----> 用户得以访问功能
- */
-
- @Data
- @TableName(value = "role", autoResultMap = true)
- public class Role extends Model<Role> {
-
- @TableId(value = "id", type = IdType.AUTO)
- public Long id;
-
- private String name;
- private String description;
-
- @TableField(typeHandler = ListHandler.class)
- private List<Long> permission;
-
- }
根据对系统用户的权限的需求分析,了解到需要对用户访问系统的功能添加许可,再利用权限角色间接限制用户对系统功能的访问。
a.数据库表主键:数据库对应的id;
b.许可所对应的功能名字:name;
c.对改功能的描述:description;
d.访问路径:path;
e.权限图片:icon;
- package com.example.system.entity;
-
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import com.baomidou.mybatisplus.extension.activerecord.Model;
- import lombok.Data;
-
- /**
- * 权限的许可:具备许可的权限角色能够访问对应的功能
- */
-
- @Data
- @TableName("permission")
- public class Permission extends Model<Permission> {
-
- /**
- * 主键
- */
- @TableId(value = "id", type = IdType.AUTO)
- private Long id;
-
- private String name;
- private String path;
- private String description;
- private String icon;
-
- }
用户在访问系统时,并不总是能够完成网络的请求与响应,当发生运行时错误,应当有响应的错误提示信息。
- package com.example.system.exception;
-
- /**
- * 运行异常的处理
- */
- public class CustomException extends RuntimeException {
-
- private String code; // 状态码
- private String msg; // 信息
-
- public CustomException(String code, String msg) {
- this.code = code;
- this.msg = msg;
- }
-
- public String getCode() {
- return code;
- }
-
- public void setCode(String code) {
- this.code = code;
- }
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
- }
全局异常统一处理
- package com.example.system.exception;
-
- import cn.hutool.log.Log;
- import cn.hutool.log.LogFactory;
- import com.example.system.common.handle.Result;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.FieldError;
- import org.springframework.web.bind.MethodArgumentNotValidException;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.List;
-
- /**
- * 全局异常的统一处理
- */
- @ControllerAdvice(basePackages="com.example.system.controller")
- public class GlobalExceptionHandler {
-
- private static final Log log = LogFactory.get();
-
- //统一异常处理@ExceptionHandler,主要用于Exception
- @ExceptionHandler(Exception.class)
- @ResponseBody//返回json串
- public Result<?> error(HttpServletRequest request, Exception e){
- log.error("异常信息:",e);
- return Result.error("-1", "系统异常");
- }
-
- // 方法参数无效异常
- @ExceptionHandler(MethodArgumentNotValidException.class)
- @ResponseBody//返回json串
- public Result<?> notValidExceptionError(MethodArgumentNotValidException e){
-
- BindingResult result = e.getBindingResult();
- StringBuilder errorMsg = new StringBuilder() ;
-
- // 提交错误信息
- if (result.hasErrors()) {
- List<FieldError> fieldErrors = result.getFieldErrors();
- errorMsg.append(fieldErrors.get(fieldErrors.size() - 1).getDefaultMessage()).append("!");
- }
-
- return Result.error("-1", errorMsg.toString());
- }
-
- // 运行时异常
- @ExceptionHandler(CustomException.class)
- @ResponseBody//返回json串
- public Result<?> customError(HttpServletRequest request, CustomException e){
- return Result.error(e.getCode(), e.getMsg());
- }
-
- }
通过继承mybatis-plus的BaseMapper来完成接口的创建。
- package com.example.system.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.example.system.entity.User;
-
- public interface UserMapper extends BaseMapper<User> {}
- package com.example.system.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.example.system.entity.Role;
-
- public interface RoleMapper extends BaseMapper<Role> {}
- package com.example.system.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.example.system.entity.Permission;
-
- public interface PermissionMapper extends BaseMapper<Permission> {}
用户进入系统访问系统功能,需要拥有一个系统认可的访问角色——用户user;而拥有一个这样的身份需要进行注册register;因为用户注册是面向用户的,仅需要用户提交一定的用户信息,此时需要系统自行对用户的权限进行设置getPermissions;当用户完成身份的注册后,访问系统需要进行登录login;最后,还需要确认用户名是否重复,进行对用户名的查询。
(2)源码
- package com.example.system.service;
-
- import cn.hutool.core.collection.CollUtil;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.example.system.entity.Permission;
- import com.example.system.entity.Role;
- import com.example.system.entity.User;
- import com.example.system.exception.CustomException;
- import com.example.system.mapper.UserMapper;
- import org.springframework.stereotype.Service;
-
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.List;
-
- @Service
- public class UserService extends ServiceImpl<UserMapper, User> {
-
- @Resource
- private RoleService roleService;
- @Resource
- private PermissionService permissionService;
-
- /**
- * 登录
- *
- * @param user
- * @return
- */
- public User login(User user) {
-
- // 获取用户登录表单数据,并查询数据库
- LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword());
- User one = getOne(queryWrapper);
-
- // 数据库中没有此数据
- if (one == null) {
- throw new CustomException("-1", "账号或密码错误");
- }
-
- // 设置用户角色权限
- one.setPermission(getPermissions(one.getId()));
- return one;
-
- }
-
- /**
- * 注册
- *
- * @param user
- * @return
- */
- public User register(User user) {
-
- // 获取表单数据,并查询数据库
- User one = getOne((Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername())));
-
- // 数据库有此数据
- if (one != null) {
- throw new CustomException("-1", "用户已注册");
- }
-
- // 未设置密码,默认设置123456
- if (user.getPassword() == null) {
- user.setPassword("123456");
- }
-
- // 默认普通用户角色
- user.setRole(CollUtil.newArrayList(2L));
- save(user);
-
- return getOne((Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername())));
-
- }
-
- /**
- * 设置权限
- *
- * @param userId
- * @return
- */
- public List<Permission> getPermissions(Long userId) {
-
- // 查询此用户,获得用户的权限角色
- User user = getById(userId);
- List<Long> role = user.getRole();
-
- // 创建空许可对象
- List<Permission> permissions = new ArrayList<>();
-
- // 判断,用户的权限角色所具备的许可,与权限角色id对应库中的权限角色的许可,少则添加
- if (role != null) {
- for (Object roleId : role) {
- Role realRole = roleService.getById((int) roleId);
- if (CollUtil.isNotEmpty(realRole.getPermission())) {
- for (Object permissionId : realRole.getPermission()) {
- Permission permission = permissionService.getById((int) permissionId);
- if (permission != null && permissions.stream().noneMatch(p -> p.getPath().equals(permission.getPath()))) {
- permissions.add(permission);
- }
- }
- }
- }
- // 将许可分配给用户
- user.setPermission(permissions);
- }
-
- return permissions;
-
- }
-
- /**
- * 根据用户名查询
- *
- * @param username
- * @return
- */
- public User getByUsername(String username) {
-
- // 获取用户名
- User one = getOne((Wrappers.<User>lambdaQuery().eq(User::getUsername, username)));
-
- // 设置权限
- one.setPermission(getPermissions(one.getId()));
-
- return one;
-
- }
-
- }
- package com.example.system.service;
-
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.example.system.entity.Role;
- import com.example.system.mapper.RoleMapper;
- import org.springframework.stereotype.Service;
-
- @Service
- public class RoleService extends ServiceImpl<RoleMapper, Role> { }
功能许可类,根据权限角色查询功能的许可;重新分配权限事务。
- package com.example.system.service;
-
- import cn.hutool.core.collection.CollUtil;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.example.system.entity.Permission;
- import com.example.system.entity.Role;
- import com.example.system.mapper.PermissionMapper;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
-
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.List;
-
- @Service
- public class PermissionService extends ServiceImpl<PermissionMapper, Permission> {
-
- @Resource
- private RoleService roleService;
-
- /**
- * 根据权限角色查询许可
- *
- * @param roles
- * @return
- */
- public List<Permission> getByRoles(List<Role> roles) {
-
- // 新建空许可对象
- List<Permission> permissions = new ArrayList<>();
-
- // 判断,权限角色所具备的许可,与其id对应的库中权限角色所具备的许可,少则添加
- for (Role role : roles) {
- Role r = roleService.getById(role.getId());
- if (CollUtil.isNotEmpty(r.getPermission())) {
- for (Object permissionId : r.getPermission()) {
- Permission permission = getById((int) permissionId);
- if (permissions.stream().noneMatch(p -> p.getPath().equals(permission.getPath()))) {
- permissions.add(permission);
- }
- }
- }
- }
-
- return permissions;
-
- }
-
- @Transactional
- public void delete(Long id) {
-
- // 删除角色分配的菜单
- removeById(id);
-
- List<Role> list = roleService.list();
-
- // 重新分配权限
- for (Role role : list) {
- List<Long> newP = new ArrayList<>();
- for (Object p : role.getPermission()) {
- Long pl = Long.valueOf(p + "");
- if (!id.equals(pl)) {
- newP.add(Long.valueOf(p + ""));
- }
- }
- role.setPermission(newP);
- roleService.updateById(role);
- }
- }
-
- }
首先,应当需要处理用户的登录login;其次,应当需要处理用户的注册register;然后还有,用户退出系统的logout;用户的查询(在线、所有、根据id、根据用户名、分页);用户的增删改查。
- package com.example.controller;
-
- import cn.hutool.core.collection.CollUtil;
- import cn.hutool.core.io.FileUtil;
- import cn.hutool.core.io.IoUtil;
- import cn.hutool.core.util.StrUtil;
- import cn.hutool.poi.excel.ExcelUtil;
- import cn.hutool.poi.excel.ExcelWriter;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.example.common.Result;
- import com.example.entity.User;
- import com.example.exception.CustomException;
- import com.example.service.LogService;
- import com.example.service.UserService;
- import org.springframework.web.bind.annotation.*;
-
- import javax.annotation.Resource;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.net.URLEncoder;
- import java.util.*;
- import java.util.concurrent.ConcurrentHashMap;
-
- @RestController
- @RequestMapping("/api/user")
- public class UserController {
- public static final ConcurrentHashMap<String, User> MAP = new ConcurrentHashMap<>();
-
- @Resource
- private UserService userService;
-
- @Resource
- private LogService logService;
- @Resource
- private HttpServletRequest request;
-
- public User getUser() {
- User user = (User) request.getSession().getAttribute("user");
- if (user == null) {
- throw new CustomException("-1", "请登录");
- }
- return user;
- }
-
-
- /**
- * 登录
- *
- * @param user
- * @param request
- * @return
- */
- @PostMapping("/login")
- public Result<User> login(@RequestBody User user, HttpServletRequest request) {
- User res = userService.login(user);
- request.getSession().setAttribute("user", res);
- MAP.put(res.getUsername(), res);
-
- logService.log(StrUtil.format("用户 {} 登录系统", user.getUsername()));
- return Result.success(res);
- }
-
- /**
- * 注册
- *
- * @param user
- * @param request
- * @return
- */
- @PostMapping("/register")
- public Result<User> register(@RequestBody User user, HttpServletRequest request) {
- if (user.getPassword() == null) {
- user.setPassword("123456");
- }
- User dbUser = userService.register(user);
- request.getSession().setAttribute("user", user);
-
- logService.log(StrUtil.format("用户 {} 注册账号成功", user.getUsername()));
- return Result.success(dbUser);
- }
-
- @GetMapping("/logout")
- public Result<?> logout(HttpServletRequest request) {
- User user = (User) request.getSession().getAttribute("user");
- if (user != null) {
- logService.log(StrUtil.format("用户 {} 退出系统", user.getUsername()));
- request.getSession().removeAttribute("user");
- MAP.remove(user.getUsername());
- }
- return Result.success();
- }
-
- @GetMapping("/online")
- public Result<Collection<User>> online(HttpServletRequest request) {
- return Result.success(MAP.values());
- }
-
- @GetMapping("/session")
- public Result<User> session() {
- return Result.success(getUser());
- }
-
- @PostMapping
- public Result<?> save(@RequestBody User user) {
- if (user.getPassword() == null) {
- user.setPassword("123456");
- }
- logService.log(StrUtil.format("新增用户:{} ", user.getUsername()));
- return Result.success(userService.save(user));
- }
-
- @PutMapping
- public Result<?> update(@RequestBody User user) {
- logService.log(StrUtil.format("更新用户:{} ", user.getUsername()));
- return Result.success(userService.updateById(user));
- }
-
- @DeleteMapping("/{id}")
- public Result<?> delete(@PathVariable Long id) {
- User user = userService.getById(id);
- logService.log(StrUtil.format("删除用户 {} ", user.getUsername()));
-
- userService.removeById(id);
- return Result.success();
- }
-
- @GetMapping("/{id}")
- public Result<User> findById(@PathVariable Long id) {
- return Result.success(userService.getById(id));
- }
-
- @GetMapping("/detail/{username}")
- public Result<User> findByUsername(@PathVariable String username) {
- return Result.success(userService.getbyUsername(username));
- }
-
- @GetMapping
- public Result<List<User>> findAll() {
- return Result.success(userService.list( Wrappers.<User>lambdaQuery().ne(User::getUsername, "admin")));
- }
-
- @GetMapping("/page")
- public Result<IPage<User>> findPage(@RequestParam(required = false, defaultValue = "") String name,
- @RequestParam(required = false, defaultValue = "1") Integer pageNum,
- @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
- LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().ne(User::getUsername, "admin").like(User::getUsername, name).orderByDesc(User::getId);
- return Result.success(userService.page(new Page<>(pageNum, pageSize), wrapper));
- }
-
- @GetMapping("/export")
- public void export(HttpServletResponse response) throws IOException {
-
- List<Map<String, Object>> list = CollUtil.newArrayList();
-
- List<User> all = userService.list();
- for (User user : all) {
- Map<String, Object> row1 = new LinkedHashMap<>();
- row1.put("名称", user.getUsername());
- row1.put("手机", user.getPhone());
- row1.put("邮箱", user.getEmail());
- list.add(row1);
- }
-
- // 2. 写excel
- ExcelWriter writer = ExcelUtil.getWriter(true);
- writer.write(list, true);
-
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
- String fileName = URLEncoder.encode("用户信息", "UTF-8");
- response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
-
- ServletOutputStream out = response.getOutputStream();
- writer.flush(out, true);
- writer.close();
- IoUtil.close(System.out);
- }
-
- @GetMapping("/upload/{fileId}")
- public Result<?> upload(@PathVariable String fileId) {
- String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
- List<String> fileNames = FileUtil.listFileNames(basePath);
- String file = fileNames.stream().filter(name -> name.contains(fileId)).findAny().orElse("");
- List<List<Object>> lists = ExcelUtil.getReader(basePath + file).read(1);
- List<User> saveList = new ArrayList<>();
- for (List<Object> row : lists) {
- User user = new User();
- user.setUsername((String) row.get(0));
- user.setNickName((String) row.get(1));
- user.setEmail((String) row.get(2));
- user.setPhone((String) row.get(3));
- saveList.add(user);
- }
- userService.saveBatch(saveList);
- return Result.success();
- }
-
- }
权限角色的增删改查;权限角色的查询(根据id、所有、分页)。
- package com.example.system.controller;
-
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.example.system.common.handle.Result;
- import com.example.system.entity.Role;
- import com.example.system.service.RoleService;
- import org.springframework.web.bind.annotation.*;
-
- import javax.annotation.Resource;
- import java.util.List;
-
- @RestController
- @RequestMapping("/api/role")
- public class RoleController {
- @Resource
- private RoleService roleService;
-
- /**
- * 增加权限角色
- *
- * @param role
- * @return
- */
- @PostMapping
- public Result<?> save(@RequestBody Role role) {
- return Result.success(roleService.save(role));
- }
-
- /**
- * 更新权限角色
- *
- * @param role
- * @return
- */
- @PutMapping
- public Result<?> update(@RequestBody Role role) {
- return Result.success(roleService.updateById(role));
- }
-
- /**
- * 根据id删除权限角色
- *
- * @param id
- * @return
- */
- @DeleteMapping("/{id}")
- public Result<?> delete(@PathVariable Long id) {
-
- roleService.removeById(id);
- return Result.success();
-
- }
-
- /**
- * 根据id查询
- *
- * @param id
- * @return
- */
- @GetMapping("/{id}")
- public Result<Role> findById(@PathVariable Long id) {
- return Result.success(roleService.getById(id));
- }
-
- /**
- * 查询所有
- *
- * @return
- */
- @GetMapping
- public Result<List<Role>> findAll() {
- return Result.success(roleService.list());
- }
-
- /**
- * 分页查询
- *
- * @param name
- * @param pageNum
- * @param pageSize
- * @return
- */
- @GetMapping("/page")
- public Result<IPage<Role>> findPage(@RequestParam(required = false, defaultValue = "") String name,
- @RequestParam(required = false, defaultValue = "1") Integer pageNum,
- @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
- return Result.success(roleService.page(new Page<>(pageNum, pageSize), Wrappers.<Role>lambdaQuery().like(Role::getName, name)));
- }
-
- }
许可的增删改查;许可的查询(根据id、所有、分页、通过权限用户)。
- package com.example.system.controller;
-
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.example.system.common.handle.Result;
- import com.example.system.entity.Permission;
- import com.example.system.entity.Role;
- import com.example.system.service.PermissionService;
- import org.springframework.web.bind.annotation.*;
-
- import javax.annotation.Resource;
- import java.util.List;
-
- @RestController
- @RequestMapping("/api/permission")
- public class PermissionController {
- @Resource
- private PermissionService permissionService;
-
- /**
- * 新增许可
- *
- * @param permission
- * @return
- */
- @PostMapping
- public Result<?> save(@RequestBody Permission permission) {
- return Result.success(permissionService.save(permission));
- }
-
- /**
- * 更新许可
- *
- * @param permission
- * @return
- */
- @PutMapping
- public Result<?> update(@RequestBody Permission permission) {
- return Result.success(permissionService.updateById(permission));
- }
-
- /**
- * 删除许可
- *
- * @param id
- * @return
- */
- @DeleteMapping("/{id}")
- public Result<?> delete(@PathVariable Long id) {
- Permission permission = permissionService.getById(id);
- permissionService.delete(id);
- return Result.success();
- }
-
- /**
- * 根据id查询许可
- *
- * @param id
- * @return
- */
- @GetMapping("/{id}")
- public Result<Permission> findById(@PathVariable Long id) {
- return Result.success(permissionService.getById(id));
- }
-
- /**
- * 查询所有
- *
- * @return
- */
- @GetMapping
- public Result<List<Permission>> findAll() {
- return Result.success(permissionService.list());
- }
-
- /**
- * 分页查询许可
- *
- * @param name
- * @param pageNum
- * @param pageSize
- * @return
- */
- @GetMapping("/page")
- public Result<IPage<Permission>> findPage(@RequestParam(required = false, defaultValue = "") String name,
- @RequestParam(required = false, defaultValue = "1") Integer pageNum,
- @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
- return Result.success(permissionService.page(new Page<>(pageNum, pageSize), Wrappers.<Permission>lambdaQuery().like(Permission::getName, name)));
- }
-
- /**
- * 通过权限角色查询权限角色所拥有的许可
- *
- * @param roles
- * @return
- */
- @PostMapping("/getByRoles")
- public Result<List<Permission>> getByRoles(@RequestBody List<Role> roles) {
- return Result.success(permissionService.getByRoles(roles));
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。