废话少说,直接步入正题。
一、项目依赖
父项目依赖(提供基础必备依赖):
<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- 基本信息 -->
<modelVersion>4.0.0</modelVersion>
<groupId>com.easystudy</groupId>
<artifactId>spring-cloud-oauther2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>spring-cloud-oauther2</name>
<description>spring-cloud-oauther2</description>
<!-- 子模块列表-->
<modules>
<module>spring-auth-common</module>
<module>spring-auth-register</module>
<module>spring-auth-server</module>
<module>spring-auth-user-service</module>
</modules>
<!-- spring boot项目 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 项目属性 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.BUILD-SNAPSHOT</spring-cloud.version>
<lombok.version>1.16.20</lombok.version>
</properties>
<!-- 项目依赖管理声明,统一管理项目依赖的版本信息,继承项目无需声明版本 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 远程仓库:中央仓库找不到时候,从远程仓库中查找 -->
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<!-- 项目依赖 -->
<dependencies>
<!-- spring web: springMVC依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--spring boot测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 监控系统健康情况的工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 修改自动检测加载工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- RESTFul接口文档:通过接口访问文档:http://localhost:8762/swagger-ui.html,8762为服务配置的监听端口,默认8080-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<!--Lombok:消除模板代码-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<!-- 编译插件 -->
<build>
<plugins>
<!-- SpringBoot编译插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
本项目依赖(本项目特别强制依赖):
<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- 基本信息 -->
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-auth-user-service</artifactId>
<name>oauth2 user service</name>
<description>oauth2用户服务</description>
<!-- 父项目 -->
<parent>
<groupId>com.easystudy</groupId>
<artifactId>spring-cloud-oauther2</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<!-- 强依赖 -->
<dependencies>
<!-- 公共信息包 -->
<dependency>
<groupId>com.easystudy</groupId>
<artifactId>spring-auth-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- spring cloud 客户注册 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- jpa注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 阿里巴巴druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 配置文件读取与对象转换 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
这里依赖了eureka注册客户端,数据库操作jpa,以及mysql连接组件、阿里巴巴数据库连接池、配置文件读取工具和日志;
二、系统配置
#服务配置
server:
#监听端口
port: 8764
spring:
application:
#服务名称
name: user-service
#jpa注解持久化配置
jpa:
#数据库类型
database: MYSQL
#显示sql
show-sql: true
#格式化sql
format-sql: true
#hibernate配置
hibernate:
#create-drop、create、update、validate
ddl-auto: update
#本地sql语言
dialect: org.hibernate.dialect.MySQL5Dialect
#数据库连接池druid
druid:
#数据库连接URL
url: jdbc:mysql://localhost:3306/zuul-auth?useUnicode=true&characterEncoding=utf-8&useSSL=false
#连接用户名
username: root
#连接密码
password: root
#使用驱动名
driver-class-name: com.mysql.jdbc.Driver
# 连接池配置----------------------
#初始连接池大小
initial-size: 5
#最小闲置连接
min-idle: 5
#最大活动连接大小
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
# 验证连接有效性
validation-query: SELECT 'x'
validation-query-timeout: 6
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
test-while-idle: true
#这里建议配置为TRUE,防止取到的连接不可用。获取链接的时候,不校验是否可用,开启会有损性能
test-on-borrow: false
#归还链接到连接池的时候校验链接是否可用
test-on-return: false
# 打开PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filters: stat,wall,log4j
#慢SQL记录:开启合并sql、开启慢查询语句,5000毫秒
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
######Druid监控配置#######
#可以更好的对sql性能进行监控
#IP:port/项目名/druid/index.html 或sql.html,可以看到各种监控
#druid默认配置登录拦截页面:如上,用户名和密码都是druid,拦截了/druid/*
#eureka集群配置
eureka:
instance:
#将IP注册到Eureka Server上,如果不配置就是机器的主机名
prefer-ip-address: true
#实例名定义为:"ip:port" 如果spring.cloud.client.ipAddress获取不到则使用spring.cloud.client.ip_address
#instance-id: ${spring.cloud.client.ip_address}:${server.port}
#隔多久去拉取服务注册信息,m默认30s
registry-fetch-interval-seconds: 30
#client发送心跳给server端的频率,m默认30s,如果server端leaseExpirationDurationInSeconds
#后没有收到client的心跳,则将摘除该instance
lease-renewal-interval-in-seconds: 10
#表示eureka server至上一次收到client的心跳之后,等待下一次心跳的超时时间,
#在这个时间内若没收到下一次心跳,则将移除该instance,默认是90秒
lease-expiration-duration-in-seconds: 30
#eureka客户端配置
client:
#注册到eureka服务器地址
service-url:
#可以配置多个
#defaultZone: http://mss-eureka1:9010/eureka/,http://mss-eureka2:9011/eureka/
defaultZone:http://localhost:8761/eureka/
# =====================Spring Boot Actuator:监控系统配置=====================
endpoints:
health:
sensitive: false
enabled: true
shutdown:
#Spring Boot Actuator的shutdown endpoint默认是关闭的
enabled: true
#自定义api地址:host:port/shutdown就可以实现优雅停机
path: /shutdown
#使用密码验证-项目中添加的有Spring Security,所有通过HTTP暴露的敏感端点都会受到保护
#默认情况下会使用基本认证(basic authentication,用户名为user,密码为应用启动时在控制台打印的密码)
sensitive: true
management:
security:
#刷新时,关闭安全验证
enabled: false
# =====================Spring Boot Actuator:监控系统配置=====================
#系统日志配置
logging:
#日志路径
config: classpath:logback.xml
#不同组件的日志显示级别
level:
org:
springframework:
web: info
备注: 这里主要配置了数据库连接池、eureka客户端配置、jpa配置、druid配置在jpa之下是自定义的需要使用spring-boot-configuration-processor读取对应的节点到对应的类中。真实的dataSource配置如下,以properties为例(这里会默认使用连接池 hikariCP):
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/oauth2?characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=5
spring.datasource.max-wait=10000
spring.datasource.min-idle=2
spring.datasource.initial-size=3
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=true
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=50)
三、数据库接口
按照oauth2讲,主要接口是loadUserByUsername,通过用户名获取对应权限即可,权限以ROLE_打头(oauth),这些权限生成oauth2的用户(用户名、密码、权限列表),然后Security通过这些权限判定是否有权限访问对应资源;
(1)权限DAO
package com.easystudy.dao;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.easystudy.model.Rights;
/**
* 用户权限操作接口
* @author Administrator
*/
@Repository
public interface RightsDao extends /*CrudRepository<Rights, Long>, */PagingAndSortingRepository<Rights, Long>{
/**
* 通过权限值获取权限详情
* @param rightValue
* @return
*/
@Query(value="select * from rights where value=:rightValue", nativeQuery=true)
public Rights findRightsByValue(@Param("rightValue") String rightValue);
}
(2)角色DAO
package com.easystudy.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.easystudy.model.Role;
/**
* 用户自定义接口
* @author Administrator
*/
@Repository
public interface RoleDao extends /*CrudRepository<Role, Long>, */PagingAndSortingRepository<Role, Long>{
/**
* 通过角色名查询角色信息
* @param username
* @return
*/
@Query(value="select * from role r where r.name=:rolename", nativeQuery=true)
public Role findByRoleName(@Param("rolename") String rolename);
/**
* 通过用户id获取用户角色列表
* @param userId
* @return
*/
@Query(value="select r.* from user u join userrole ur join role r where u.id=ur.user_id and ur.role_id=r.id and u.id=:userId", nativeQuery=true)
public List<Role> findRolesByUserId(@Param("userId") Long userId);
/**
* 通过用户名获取用户角色列表
* @param userName
* @return
*/
@Query(value="select r.* from user u join userrole ur join role r where u.id=ur.user_id and ur.role_id=r.id and u.username=:username", nativeQuery=true)
public List<Role> findRolesByUserName(@Param("username") String userName);
}
(3)角色权限DAO
package com.easystudy.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.easystudy.model.RoleRights;
/**
* 用户自定义接口
* @author Administrator
*/
@Repository
public interface RoleRightsDao extends /*CrudRepository<RoleRights, Long>, */PagingAndSortingRepository<RoleRights, Long>{
/**
* 通过角色id和权限id查询某角色权限信息
* @param username
* @return
*/
@Query(value="select * from rolerights rr where rr.role_id=:roleId and rr.right_id=:rightId", nativeQuery=true)
public RoleRights findByRoleIdAndRightId(@Param("roleId") Long roleId, @Param("rightId") Long rightId);
/**
* 通过角色id查询角色所有权限
* @param username
* @return
*/
@Query(value="select * from rolerights rr where rr.role_id=:roleId", nativeQuery=true)
public List<RoleRights> findByRoleId(@Param("roleId") Long roleId);
/**
* 通过用户id清空角色权限
* @param userId
* @return
*/
@Modifying
@Query(value="delete from rolerights rr where rr.role_id=:roleId", nativeQuery=true)
public void deleteByRoleId(@Param("roleId") Long roleId);
}
(4)用户DAO
package com.easystudy.dao;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.easystudy.model.User;
/**
* 用户自定义接口
* @author Administrator
*/
@Repository
public interface UserDao extends /*CrudRepository<User, Long>, */PagingAndSortingRepository<User, Long>{
/**
* 自定义查询nativeQuery=true说明为原生sql语句
* 1代表的是方法参数里面的顺序:此处为用户名
* @param username
* @return
*/
@Query(value="select * from user u where u.username=:username",nativeQuery=true)
public User findByUsername(@Param("username") String username);
/**
* 根据用户id更新用户名称
*/
@Modifying
@Query(value="update user u set u.name=:name where id=:id", nativeQuery=true)
public void updateNameById(@Param("id") Long id, @Param("name") String name);
}
(5)用户权限DAO
package com.easystudy.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.easystudy.model.UserRole;
/**
* 用户角色自定义接口
* @author Administrator
*/
@Repository
public interface UserRoleDao extends /*CrudRepository<UserRole, Long>, */PagingAndSortingRepository<UserRole, Long>{
/**
* 通过用户id和角色id获取用户角色
* @param username
* @return
*/
@Query(value="select * from userrole ur where ur.user_id=:userId and ur.role_id=:roleId",nativeQuery=true)
public UserRole findByUserIdAndRoleId(@Param("userId") Long userId, @Param("roleId") Long roleId);
/**
* 通过用户id获取用户角色
* @param username
* @return
*/
@Query(value="select * from userrole ur where ur.user_id=:userId",nativeQuery=true)
public List<UserRole> findByUserId(@Param("userId") Long userId);
/**
* 通过用户id清空用户角色
*/
@Modifying
@Query(value="delete from userrole ur where ur.user_id=:userId", nativeQuery=true)
public void deleteByUserId(@Param("userId") Long id);
}
四、服务层实现
这里要说明一下,这里不像hibernate的template模板一样,无法实现一层baseServerImpl,因为接口类存在泛型的情况下可能表示多个实现,使用接口autowired无法载入,所以每一个service接口有实现了baseservice的相关接口(这层本来可以用泛型提取,保证代码复用,减少冗余和错误的);
(1)服务基础接口
package com.easystudy.service;
import java.util.List;
/**
* 自定义查询nativeQuery=true说明为原生sql语句
* 1代表的是方法参数里面的顺序:此处为用户名
* 例如:
* nativeQuery表示原生的sql语句(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作
* @Query(value="select * from user u where u.username=:username",nativeQuery=true)
* @Query("update Task t set t.taskName = ?1 where t.id = ?2")
* @Query(value = "select name,author,price from Book b where b.name like %:name%")
* SPEL表达式
* @Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
* @param <T>
*/
public interface BaseService<T> {
/**
* 往数据库插入一条记录,如果已存在则抛异常
* @param o
*/
public void add(T o);
/**
* 往数据库插入n条记录,如果已存在则抛异常
* @param o
*/
public void add(List<T> o);
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
public void delete(Long id);
/**
* 往数据库删除一条记录
* @param o
*/
public void delete(T o);
/**
* 往数据库删除列表中的所有记录
* @param o
*/
public void delete(List<T> o);
/**
* 根据id查找
* @param id 查对对象的id
* @return 返回得到的结果
*/
T find(Long id);
/**
* 根据id列表查找所有对象
* @param ids 查对对象的id列表
* @return 返回得到的结果
*/
List<T> findAll(List<Long> ids);
/**
* 获取表中记录条数
*/
Long count();
/**
* 查找表中所有对象
* @param entityClass 表对应的实体类
* @return 返回得到的结果
*/
List<T> findAll();
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @return 返回得到的结果集
*/
public List<T> findAll(Integer pageIndex, Integer pageSize);
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @param sortColum 排序的列
* @param asc 是否升序排列
* @return 返回得到的结果集
*/
public List<T> findAll(Integer pageIndex, Integer pageSize, String sortColum, boolean asc);
}
(2)权限服务接口
接口类:
package com.easystudy.service;
import com.easystudy.model.Rights;
public interface RightService extends BaseService<Rights>{
/**
* 通过权限值获取权限详情
* @param rightValue
* @return
*/
public Rights findRightsByValue(String rightValue);
}
接口实现:
package com.easystudy.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.easystudy.dao.RightsDao;
import com.easystudy.model.Rights;
import com.easystudy.service.RightService;
@Service
public class RightServiceImpl implements RightService{
@Autowired
protected RightsDao dao;
/**
* 往数据库插入一条记录,如果已存在则抛异常
* @param o
*/
@Override
public void add(Rights o) {
dao.save(o);
}
/**
* 往数据库插入n条记录,如果已存在则抛异常
* @param o
*/
@Override
public void add(List<Rights> o) {
dao.saveAll(o);
}
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
@Override
public void delete(Long id) {
dao.deleteById(id);
}
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
@Override
public void delete(Rights o) {
dao.delete(o);
}
/**
* 往数据库删除列表中的所有记录
* @param o
*/
@Override
public void delete(List<Rights> o) {
dao.deleteAll(o);
}
/**
* 根据id查找
* @param id 查对对象的id
* @return 返回得到的结果
*/
@Override
public Rights find(Long id) {
Optional<Rights> op = dao.findById(id);
// Rights r = null;
// op.ifPresent((right)->{
// //right;
// });
if(op != null && op.isPresent()){
return op.get();
}
return null;
}
/**
* 根据id列表查找所有对象
* @param ids 查对对象的id列表
* @return 返回得到的结果
*/
@Override
public List<Rights> findAll(List<Long> ids) {
Iterable<Rights> iterable = dao.findAllById(ids);
if(iterable != null){
List<Rights> list = new ArrayList<Rights>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 获取表中记录条数
*/
@Override
public Long count() {
return dao.count();
}
/**
* 查找表中所有对象
* @param entityClass 表对应的实体类
* @return 返回得到的结果
*/
@Override
public List<Rights> findAll() {
Iterable<Rights> iterable = dao.findAll();
if(iterable != null){
List<Rights> list = new ArrayList<Rights>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @return 返回得到的结果集
*/
@Override
public List<Rights> findAll(Integer pageIndex, Integer pageSize) {
if(pageIndex <= 0) pageIndex = 1;
Pageable page = PageRequest.of(pageIndex, pageSize);
Iterable<Rights> iterable = dao.findAll(page);
if(iterable != null){
List<Rights> list = new ArrayList<Rights>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @param sortColum 排序的列
* @param asc 是否升序排列
* @return 返回得到的结果集
*/
@Override
public List<Rights> findAll(Integer pageIndex, Integer pageSize, String sortColum, boolean asc) {
if(pageIndex <= 0) pageIndex = 1;
// 分页
Pageable page = null;
if(sortColum != null && !sortColum.isEmpty()){
// 排序
Sort sort = null;
if(asc){
sort = Sort.by(Sort.Direction.ASC, sortColum);
}else{
sort = Sort.by(Sort.Direction.DESC, sortColum);
}
page = PageRequest.of(pageIndex, pageSize, sort);
}else{
page = PageRequest.of(pageIndex, pageSize);
}
// 检索转化
Iterable<Rights> iterable = dao.findAll(page);
if(iterable != null){
List<Rights> list = new ArrayList<Rights>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 通过权限值获取权限详情
* @param rightValue
* @return
*/
@Override
public Rights findRightsByValue(String rightValue) {
return dao.findRightsByValue(rightValue);
}
}
(2)角色服务接口
接口类:
package com.easystudy.service;
import java.util.List;
import com.easystudy.model.Role;
/**
* 角色专门的服务接口
* @author Administrator
*
*/
public interface RoleService extends BaseService<Role>{
/**
* 通过角色名称获取角色信息
* @param name
* @return
*/
public Role findByRoleName(String name);
/**
* 通过用户id获取用户角色列表
* @param userName
* @return
*/
public List<Role> findRolesByUserId(Long userId);
/**
* 通过用户id获取用户角色列表
* @param userName
* @return
*/
public List<Role> findRolesByUserName(String userName);
}
接口实现:
package com.easystudy.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.easystudy.dao.RoleDao;
import com.easystudy.model.Role;
import com.easystudy.service.RoleService;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
protected RoleDao dao;
/**
* 往数据库插入一条记录,如果已存在则抛异常
* @param o
*/
@Override
public void add(Role o) {
dao.save(o);
}
/**
* 往数据库插入n条记录,如果已存在则抛异常
* @param o
*/
@Override
public void add(List<Role> o) {
dao.saveAll(o);
}
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
@Override
public void delete(Long id) {
dao.deleteById(id);
}
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
@Override
public void delete(Role o) {
dao.delete(o);
}
/**
* 往数据库删除列表中的所有记录
* @param o
*/
@Override
public void delete(List<Role> o) {
dao.deleteAll(o);
}
/**
* 根据id查找
* @param id 查对对象的id
* @return 返回得到的结果
*/
@Override
public Role find(Long id) {
Optional<Role> op = dao.findById(id);
if(op != null && op.isPresent()){
return op.get();
}
return null;
}
/**
* 根据id列表查找所有对象
* @param ids 查对对象的id列表
* @return 返回得到的结果
*/
@Override
public List<Role> findAll(List<Long> ids) {
Iterable<Role> iterable = dao.findAllById(ids);
if(iterable != null){
List<Role> list = new ArrayList<Role>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 获取表中记录条数
*/
@Override
public Long count() {
return dao.count();
}
/**
* 查找表中所有对象
* @param entityClass 表对应的实体类
* @return 返回得到的结果
*/
@Override
public List<Role> findAll() {
Iterable<Role> iterable = dao.findAll();
if(iterable != null){
List<Role> list = new ArrayList<Role>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @return 返回得到的结果集
*/
@Override
public List<Role> findAll(Integer pageIndex, Integer pageSize) {
if(pageIndex <= 0) pageIndex = 1;
Pageable page = PageRequest.of(pageIndex, pageSize);
Iterable<Role> iterable = dao.findAll(page);
if(iterable != null){
List<Role> list = new ArrayList<Role>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @param sortColum 排序的列
* @param asc 是否升序排列
* @return 返回得到的结果集
*/
@Override
public List<Role> findAll(Integer pageIndex, Integer pageSize, String sortColum, boolean asc) {
if(pageIndex <= 0) pageIndex = 1;
// 分页
Pageable page = null;
if(sortColum != null && !sortColum.isEmpty()){
// 排序
Sort sort = null;
if(asc){
sort = Sort.by(Sort.Direction.ASC, sortColum);
}else{
sort = Sort.by(Sort.Direction.DESC, sortColum);
}
page = PageRequest.of(pageIndex, pageSize, sort);
}else{
page = PageRequest.of(pageIndex, pageSize);
}
// 检索转化
Iterable<Role> iterable = dao.findAll(page);
if(iterable != null){
List<Role> list = new ArrayList<Role>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 通过角色名查询角色信息
* @param username
* @return
*/
@Override
public Role findByRoleName(String name) {
return dao.findByRoleName(name);
}
/**
* 通过用户id获取用户角色列表
* @param userId
* @return
*/
@Override
public List<Role> findRolesByUserId(Long userId) {
return dao.findRolesByUserId(userId);
}
/**
* 通过用户名获取用户角色列表
* @param userId
* @return
*/
@Override
public List<Role> findRolesByUserName(String userName) {
return dao.findRolesByUserName(userName);
}
}
(3)用户服务接口
接口类:
package com.easystudy.service;
import com.easystudy.model.User;
/**
* 提供用户专职的服务接口
* @author Administrator
*/
public interface UserService extends BaseService<User>{
/**
* 用户用户名获取用户信息
* @param username
* @return
*/
public User findByUsername(String username);
/**
* 根据用户id更新用户名称
* @param id
* @param name
*/
public void updateNameById(Long id, String name);
}
接口实现:
package com.easystudy.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.easystudy.dao.UserDao;
import com.easystudy.model.User;
import com.easystudy.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
protected UserDao dao;
/**
* 往数据库插入一条记录,如果已存在则抛异常
* @param o
*/
@Override
public void add(User o) {
dao.save(o);
}
/**
* 往数据库插入n条记录,如果已存在则抛异常
* @param o
*/
@Override
public void add(List<User> o) {
dao.saveAll(o);
}
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
@Override
public void delete(Long id) {
dao.deleteById(id);
}
/**
* 根据id往数据库删除一条记录
* @param id 删除对象的id
*/
@Override
public void delete(User o) {
dao.delete(o);
}
/**
* 往数据库删除列表中的所有记录
* @param o
*/
@Override
public void delete(List<User> o) {
dao.deleteAll(o);
}
/**
* 根据id查找
* @param id 查对对象的id
* @return 返回得到的结果
*/
@Override
public User find(Long id) {
Optional<User> op = dao.findById(id);
if(op != null && op.isPresent()){
return op.get();
}
return null;
}
/**
* 根据id列表查找所有对象
* @param ids 查对对象的id列表
* @return 返回得到的结果
*/
@Override
public List<User> findAll(List<Long> ids) {
Iterable<User> iterable = dao.findAllById(ids);
if(iterable != null){
List<User> list = new ArrayList<User>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 获取表中记录条数
*/
@Override
public Long count() {
return dao.count();
}
/**
* 查找表中所有对象
* @param entityClass 表对应的实体类
* @return 返回得到的结果
*/
@Override
public List<User> findAll() {
Iterable<User> iterable = dao.findAll();
if(iterable != null){
List<User> list = new ArrayList<User>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @return 返回得到的结果集
*/
@Override
public List<User> findAll(Integer pageIndex, Integer pageSize) {
if(pageIndex <= 0) pageIndex = 1;
Pageable page = PageRequest.of(pageIndex, pageSize);
Iterable<User> iterable = dao.findAll(page);
if(iterable != null){
List<User> list = new ArrayList<User>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 根据条件分页查询
* @param entityClass 表对应的实体类
* @param pageIndex 初始页-从1开始
* @param pageSize 每页数量
* @param sortColum 排序的列
* @param asc 是否升序排列
* @return 返回得到的结果集
*/
@Override
public List<User> findAll(Integer pageIndex, Integer pageSize, String sortColum, boolean asc) {
if(pageIndex <= 0) pageIndex = 1;
// 分页
Pageable page = null;
if(sortColum != null && !sortColum.isEmpty()){
// 排序
Sort sort = null;
if(asc){
sort = Sort.by(Sort.Direction.ASC, sortColum);
}else{
sort = Sort.by(Sort.Direction.DESC, sortColum);
}
page = PageRequest.of(pageIndex, pageSize, sort);
}else{
page = PageRequest.of(pageIndex, pageSize);
}
// 检索转化
Iterable<User> iterable = dao.findAll(page);
if(iterable != null){
List<User> list = new ArrayList<User>();
iterable.forEach(single -> {list.add(single);});
if(list.size() > 0)
return list;
}
return null;
}
/**
* 通过用户名查找用户信息
*/
@Override
public User findByUsername(String username) {
return dao.findByUsername(username);
}
/**
* 根据用户id更新用户名称
* @param id
* @param name
*/
@Override
public void updateNameById(Long id, String name) {
dao.updateNameById(id, name);
}
}
五、druid数据源配置
(1)数据源配置
package com.easystudy.druid;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "spring.jpa.druid", ignoreUnknownFields=true)
public class DruidDataSourceConfig {
private String url;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private String validationQuery;
private int validationQueryTimeout;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String connectionProperties;
// 解决 spring.datasource.filters=stat,wall,log4j 无法正常注册
@Bean
@Primary // 在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
// configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setValidationQueryTimeout(validationQueryTimeout);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: " + e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
(2)sql监控配置
package com.easystudy.druid;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
/**
* @SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类
* 并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名
*
* 此处配置druid拦截的页面以及druid初始化参数,同web.xml配置方式-filter-mapping和初始化参数context-param
*/
@Slf4j
@SpringBootConfiguration
public class DruidMonitorConfig {
/**
* 配置拦截过滤器过滤地址、访问源、初始化参数等
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletRegistrationBean servletRegistrationBean() {
log.info("初始化 Druid 监控 Servlet.");
// sevlet中配置 druid拦截的url_patttrn
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
// IP白名单
servletRegistrationBean.addInitParameter("allow", "192.168.12.8,127.0.0.1");
// IP黑名单(共同存在时,deny优先于allow)
servletRegistrationBean.addInitParameter("deny", "192.168.12.9");
// 控制台管理用户名和密码
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
// 是否能够重置数据,是否禁用HTML页面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "true");
return servletRegistrationBean;
}
/**
* 有很多请求要直接请求进来,不需要鉴权登陆druid页面的
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
(3)状态过滤,不拦截不涉及到sql的请求
package com.easystudy.druid;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* druid我们都很熟悉,是一款非常好用的数据连接池,但是很多开发者不知, druid除了数据连接池,
* 还集成了对站点的URL进行统计的功能,下面就详细的为大家讲解一下如何配置druid的url统计。
* 比如统计哪些sql语句执行慢,需要优化,就是通过过滤器来实现sql统计的
* WebStatFilter用于采集web-jdbc关联监控的数据,此处配置的是druid监控的数据过滤器.
* exlusions配置:经常需要排除一些不必要的url,比如.js,/jslib/等等。配置在init-param中
*
* 通过配置文件配置也可以:
*
#druid WebStatFilter监控配置
spring.datasource.druid.web-stat-filter.enabled= true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=10
spring.datasource.druid.web-stat-filter.principal-session-name=
spring.datasource.druid.web-stat-filter.principal-cookie-name=
spring.datasource.druid.web-stat-filter.profile-enable=
*/
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
initParams = {
// 忽略资源
@WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")
}
)
public class DruidStatFilter extends WebStatFilter {
}
(4)资源状态监控
package com.easystudy.druid;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;
/**
* druid数据源状态监控.
* 也可以通过配置文件配置:
* #druid StatViewServlet监控配置
spring.datasource.druid.stat-view-servlet.enabled= true
spring.datasource.druid.stat-view-servlet.url-pattern= /druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
spring.datasource.druid.stat-view-servlet.allow=192.168.1.110,127.0.0.1
spring.datasource.druid.stat-view-servlet.deny=192.168.16.111
*/
@WebServlet(urlPatterns = "/druid/*", initParams = {
// IP白名单 (没有配置或者为空,则允许所有访问)
@WebInitParam(name = "allow", value = "192.168.12.8,127.0.0.1"),
// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name = "deny", value = "192.168.12.9"),
// 用户名
@WebInitParam(name = "loginUsername", value = "admin"),
// 密码
@WebInitParam(name = "loginPassword", value = "admin"),
// 禁用HTML页面上的“Reset All”功能
@WebInitParam(name = "resetEnable", value = "false") })
@SuppressWarnings("serial")
public class DruidStatViewServlet extends StatViewServlet {
}
六、控制层实现
(1)用户信息
package com.easystudy.controller;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.easystudy.error.ReturnValue;
import com.easystudy.model.User;
import com.easystudy.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
protected UserService userService;
/**
* 通过用户名获取用户信息
* @param username
* @return
* @throws JsonProcessingException
*/
@RequestMapping(value = "/findByUserName/{username}", method = RequestMethod.GET)
public ReturnValue<User> findByUserName(@PathVariable("username") String username) throws JsonProcessingException{
User user = userService.findByUsername(username);
ReturnValue<User> ret = new ReturnValue<User>(user);
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(ret);
System.out.println(str);
return ret;
}
/**
* 获取所有用户信息
* @return
*/
@RequestMapping(value = "/findAllUser", method = RequestMethod.GET)
public ReturnValue<List<User>> findAllUser(){
List<User> users = userService.findAll();
System.out.println("查找所有用户:" + users);
return new ReturnValue<List<User>>(users);
}
/**
* 根据用户id删除用户
* @param id 用户id
* @return
*/
@RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE)
public ReturnValue<String> deleteUser(@PathVariable("id") Long id){
userService.delete(id);
return new ReturnValue<String>();
}
/**
* 添加用户
* @param username
* @param password
* @param name
* @return
*/
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public ReturnValue<User> addUser(@RequestParam(name="username", required=true) String username, @RequestParam(name="password", required=true) String password,
@RequestParam(name="name", required=true) String name, @RequestParam(name="sex", required=false, defaultValue="0") Long sex){
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setName(name);
user.setSex(sex);
userService.add(user);
return new ReturnValue<User>(user);
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
User user = new User();
user.setUsername("lixx");
user.setPassword("123456");
user.setName("李强");
user.setBirthday(new Date());
user.setEmail("lixiang6153@126.com");
user.setPhone("18689250776");
user.setSex(0L);
String str = mapper.writeValueAsString(user);
System.out.println(str);
User user2 = mapper.readValue(str, User.class);
System.out.println("用户名:" + user2.getName());
ReturnValue<User> ret = new ReturnValue<User>(user);
String response = mapper.writeValueAsString(ret);
System.out.println(response);
}
}
(2)权限信息
package com.easystudy.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.easystudy.error.ReturnValue;
import com.easystudy.model.Rights;
import com.easystudy.service.RightService;
@RestController
@RequestMapping("/rights")
public class RightsController {
@Autowired
protected RightService rightService;
/**
* 通过角色id获取角色权限列表
* @param username
* @return
*/
@RequestMapping(value = "/findByRightId/{rightId}", method = RequestMethod.GET)
public ReturnValue<Rights> findByRightId(@PathVariable("rightId") Long rightId){
Rights right = rightService.find(rightId);
return new ReturnValue<Rights>(right);
}
}
(3)角色信息
package com.easystudy.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.easystudy.error.ReturnValue;
import com.easystudy.model.RoleRights;
import com.easystudy.service.RoleRightsService;
@RestController
@RequestMapping("/roleRights")
public class RoleController {
@Autowired
protected RoleRightsService roleRightsService;
/**
* 通过角色id获取角色权限列表
* @param username
* @return
*/
@RequestMapping(value = "/findByRoleId/{roleId}", method = RequestMethod.GET)
public ReturnValue<List<RoleRights>> findRolesByUserId(@PathVariable("roleId") Long roleId){
List<RoleRights> roles = roleRightsService.findByRoleId(roleId);
return new ReturnValue<List<RoleRights>>(roles);
}
}
七、入口实现
(1)入口实现
package com.easystudy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@EntityScan("com.easystudy.*")
public class UserServiceApp {
public static void main(String[] args) {
SpringApplication.run(UserServiceApp.class, args);
}
}
(2)初始化表
package com.easystudy;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.easystudy.model.Rights;
import com.easystudy.model.Role;
import com.easystudy.model.RoleRights;
import com.easystudy.model.User;
import com.easystudy.model.UserRole;
import com.easystudy.service.RightService;
import com.easystudy.service.RoleRightsService;
import com.easystudy.service.RoleService;
import com.easystudy.service.UserRoleService;
import com.easystudy.service.UserService;
/**
* 启动-数据库加载
* @author Administrator
* 启动参数加载释放方式有如下几种方式:
* 1、实现CommandLineRunner命令行运行接口
* 2、使用过滤器,在实现类中标注注解:
* @WebFilter(filterName="myFilter",urlPatterns="/*"),属性filterName声明过滤器的名称,可选;属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明,必选
* 3、实现ServletContext监听器,在实现类中标注注解:
* @WebListener,实现ServletContextListener接口(即标注@WebListener并且实现implements ServletContextListener)
* 在启动类中添加@ServletComponentScan扫描自定义servlet
* 4、实现HttpSessionListener监听器,在实现类中标注注解:
* @WebListener,实现HttpSessionListener接口(即标注@WebListener并且实现implements HttpSessionListener)
* 5、在主容器的main函数实现自己的初始化(即SpringApplication.run(UserServiceApp.class, args)之后添加)
*/
@Component
@Order(1)
public class DBInit implements CommandLineRunner{
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private RightService rightService;
@Autowired
private UserRoleService userRoleService;
@Autowired
private RoleRightsService roleRightsService;
@Override
public void run(String... args) throws Exception {
// 秘钥加密存储到数据库--此处手动填写到数据库
String text = new BCryptPasswordEncoder().encode("test_client_secret");
System.out.println(text);
// 创建用户
List<User> users = initUser();
// 创建权限
List<Rights> rights = initRights();
// 创建角色
List<Role> roles = initRoles();
// 用户角色
// 超级管理员
initUserRole(users.get(0), roles);
// 管理员
List<Role> roles2 = new ArrayList<Role>();
roles2.add(roles.get(1));
roles2.add(roles.get(2));
initUserRole(users.get(1), roles2);
// 操作员
List<Role> roles3 = new ArrayList<Role>();
roles3.add(roles.get(2));
initUserRole(users.get(2), roles3);
// 角色权限
// 超级管理员权限
initRoleRights(roles.get(0), rights);
// 管理员权限
List<Rights> right2 = new ArrayList<Rights>();
right2.add(rights.get(1));
right2.add(rights.get(2));
initRoleRights(roles.get(1), right2);
// 操作员权限
List<Rights> right3 = new ArrayList<Rights>();
right3.add(rights.get(2));
initRoleRights(roles.get(2), right3);
}
private void initRoleRights(Role role, List<Rights> rights) {
for (Rights right : rights) {
RoleRights rr = roleRightsService.findByRoleIdAndRightId(role.getId().longValue(), right.getId().longValue());
if(null == rr){
rr = new RoleRights();
rr.setRole_id(role.getId());
rr.setRight_id(right.getId());
roleRightsService.add(rr);
}
}
}
private void initUserRole(User user, List<Role> roles) {
for (Role r : roles) {
UserRole ur = userRoleService.findByUserIdAndRoleId(user.getId().longValue(), r.getId().longValue());
if(null == ur){
ur = new UserRole();
ur.setUser_id(user.getId());
ur.setRole_id(r.getId());
userRoleService.add(ur);
}
}
}
List<User> initUser(){
User user = userService.findByUsername("lixx");
if(null == user){
// 超级管理员权限
user = new User();
user.setUsername("lixx");
//user.setPassword("dw123456");
user.setPassword(new BCryptPasswordEncoder().encode("dw123456"));
user.setName("李强");
user.setBirthday(new Date());
user.setEmail("lixiang6153@126.com");
user.setPhone("18689250776");
user.setSex(0L);
userService.add(user);
}
User user2 = userService.findByUsername("admin");
if(null == user2){
// 超级管理员权限
user2 = new User();
user2.setUsername("admin");
user2.setPassword(new BCryptPasswordEncoder().encode("dw123456"));
//user2.setPassword("dw123456");
user2.setName("管理员");
user2.setBirthday(new Date());
user2.setSex(0L);
userService.add(user2);
}
User user3 = userService.findByUsername("operator");
if(null == user3){
// 超级管理员权限
user3 = new User();
user3.setUsername("operator");
user3.setPassword(new BCryptPasswordEncoder().encode("dw123456"));
//user3.setPassword("dw123456");
user3.setName("操作员");
user3.setBirthday(new Date());
user3.setSex(1L);
userService.add(user3);
}
List<User> users = new ArrayList<User>();
users.add(user);
users.add(user2);
users.add(user3);
return users;
}
List<Role> initRoles(){
Role role1 = roleService.findByRoleName("ROLE_SUPER");
if(null == role1){
role1 = new Role();
role1.setName("ROLE_SUPER");
role1.setStatus(1L);
role1.setValue("001");
role1.setTips("超级管理员");
roleService.add(role1);
}
Role role2 = roleService.findByRoleName("ROLE_ADMIN");
if(null == role2){
role2 = new Role();
role2.setName("ROLE_ADMIN");
role2.setStatus(1L);
role2.setValue("002");
role2.setTips("管理员");
roleService.add(role2);
}
Role role3 = roleService.findByRoleName("ROLE_OPERATOR");
if(null == role3){
role3 = new Role();
role3.setName("ROLE_OPERATOR");
role3.setStatus(1L);
role3.setValue("003");
role3.setTips("操作员");
roleService.add(role3);
}
List<Role> roles = new ArrayList<Role>();
roles.add(role1);
roles.add(role2);
roles.add(role3);
return roles;
}
List<Rights> initRights(){
Rights right1 = rightService.findRightsByValue("001");
if(null == right1){
right1 = new Rights();
right1.setName("ROLE_HOME");
right1.setValue("001");
rightService.add(right1);
}
Rights right2 = rightService.findRightsByValue("002");
if(null == right2){
right2 = new Rights();
right2.setName("ROLE_DEVICE");
right2.setValue("002");
rightService.add(right2);
}
Rights right3 = rightService.findRightsByValue("003");
if(null == right3){
right3 = new Rights();
right3.setName("ROLE_VIDEO");
right3.setValue("003");
rightService.add(right3);
}
List<Rights> rights = new ArrayList<Rights>();
rights.add(right1);
rights.add(right2);
rights.add(right3);
return rights;
}
}
到此用户服务基本完成。其他模块可以使用feign调用用户接口了。
快来成为我的朋友或合作伙伴,一起交流,一起进步!
QQ群:961179337
微信:lixiang6153
邮箱:lixx2048@163.com
公众号:IT技术快餐
更多资料等你来拿!