SpringBoot项目的搭建
上次演示了如何搭建SSM框架(传送门:https://www.cnblogs.com/ljhblogs/p/11039255.html),本次演示SpringBoot框架的搭建以及集成Shiro,Druid,Mybatis等框架。
搭建之前,先回顾一下SSM框架的大致搭建过程:
- 配置maven项目依赖
- 配置 web.xml,配置Spring MVC核心控制器DispatcherServlet,Shiro监控,编码过滤器,静态文件过滤,监听器,加载 spring-mvc、spring-myabtis与其他Spring集成框架
- 在spring-mvc.xml文件中配置视图解析器,文件上传,AOP,拦截器等
- 在spring-myabtis.xml文件中配置数据库连接、 映射Dao层、事务管理等
- 在spring-shiro.xml文件中配置自定义身份认证、加密、权限设置、会话管理等
SpringBoot是为了简化Spring应用开发而生的,是整个Spring技术栈的大整合,它遵循约定大于配置的原则(内置了大量的自动配置),因此接下来整个SpringBoot框架搭建就简单了很多:
一.初始化搭建
可直接在Spring官方提供的搭建网站进行初始化搭建:https://start.spring.io/
填写项目相关基本信息后点击下方生成项目按钮即可得到一个最基本的SpringBoot项目:
二.配置项目依赖pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 6 <modelVersion>4.0.0</modelVersion> 7 8 <groupId>com.mySpringBoot</groupId> 9 <artifactId>mySpringBoot</artifactId> 10 <version>0.0.1-SNAPSHOT</version> 11 <name>mySpringBoot</name> 12 <description>ljh</description> 13 14 <!-- 继承自父项目SpringBoot,SpringBoot的默认配置信息以及默认添加的依赖,导入依赖默认不需要写版本(没有在dependencies里面管理的依赖自然需要声明版本号) --> 15 <parent> 16 <groupId>org.springframework.boot</groupId> 17 <artifactId>spring-boot-starter-parent</artifactId> 18 <version>2.1.6.RELEASE</version> 19 <relativePath/> 20 </parent> 21 22 <!-- 版本管理 --> 23 <properties> 24 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 25 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 26 <java.version>1.8</java.version> 27 <shiro.version>1.2.3</shiro.version> 28 <mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version> 29 <mybatisplus.version>2.3.1</mybatisplus.version> 30 <druid.version>1.1.3</druid.version> 31 </properties> 32 33 <!-- 项目依赖 --> 34 <dependencies> 41 <!-- spring-boot-web依赖 --> 42 <dependency> 43 <groupId>org.springframework.boot</groupId> 44 <artifactId>spring-boot-starter-web</artifactId> 45 </dependency> 46 47 <!-- spring-boot-jdbc依赖 --> 48 <dependency> 49 <groupId>org.springframework.boot</groupId> 50 <artifactId>spring-boot-starter-jdbc</artifactId> 51 </dependency> 52 53 <!-- spring-boot-aop依赖 --> 54 <dependency> 55 <groupId>org.springframework.boot</groupId> 56 <artifactId>spring-boot-starter-aop</artifactId> 57 </dependency> 58 59 <!-- spring-boot-test测试依赖--> 60 <dependency> 61 <groupId>org.springframework.boot</groupId> 62 <artifactId>spring-boot-starter-test</artifactId> 63 <scope>test</scope> 64 </dependency> 65 66 <!-- spring-boot热部署 --> 67 <dependency> 68 <groupId>org.springframework.boot</groupId> 69 <artifactId>spring-boot-devtools</artifactId> 70 <optional>true</optional> 71 </dependency> 72 73 <!-- mysql连接依赖 --> 74 <dependency> 75 <groupId>mysql</groupId> 76 <artifactId>mysql-connector-java</artifactId> 77 </dependency> 78 79 <!-- 阿里连接池Druid依赖 --> 80 <dependency> 81 <groupId>com.alibaba</groupId> 82 <artifactId>druid</artifactId> 83 <version>${druid.version}</version> 84 </dependency> 85 86 <!-- MyBatis-Plus依赖 --> 87 <dependency> 88 <groupId>com.baomidou</groupId> 89 <artifactId>mybatisplus-spring-boot-starter</artifactId> 90 <version>${mybatisplus-spring-boot-starter.version}</version> 91 </dependency> 92 93 <dependency> 94 <groupId>com.baomidou</groupId> 95 <artifactId>mybatis-plus</artifactId> 96 <version>${mybatisplus.version}</version> 97 </dependency> 98 99 <!-- MyBatis分页插件PageHelper依赖 --> 100 <dependency> 101 <groupId>com.github.pagehelper</groupId> 102 <artifactId>pagehelper-spring-boot-starter</artifactId> 103 <version>1.2.3</version> 104 </dependency> 105 106 <!-- spring切面 --> 107 <dependency> 108 <groupId>org.springframework</groupId> 109 <artifactId>spring-aspects</artifactId> 110 </dependency> 111 112 <!-- freemaker模版引擎依赖 --> 113 <dependency> 114 <groupId>org.springframework.boot</groupId> 115 <artifactId>spring-boot-starter-freemarker</artifactId> 116 </dependency> 117 118 <dependency> 119 <groupId>net.mingsoft</groupId> 120 <artifactId>shiro-freemarker-tags</artifactId> 121 <version>0.1</version> 122 <exclusions> 123 <exclusion> 124 <artifactId>log4j</artifactId> 125 <groupId>log4j</groupId> 126 </exclusion> 127 </exclusions> 128 </dependency> 129 130 <!-- 模板引擎 代码生成 --> 131 <dependency> 132 <groupId>org.apache.velocity</groupId> 133 <artifactId>velocity</artifactId> 134 <version>1.7</version> 135 </dependency> 136 137 <!-- Shiro安全验证依赖 --> 138 <dependency> 139 <groupId>org.apache.shiro</groupId> 140 <artifactId>shiro-core</artifactId> 141 <version>${shiro.version}</version> 142 </dependency> 143 144 <dependency> 145 <groupId>org.apache.shiro</groupId> 146 <artifactId>shiro-web</artifactId> 147 <version>${shiro.version}</version> 148 </dependency> 149 150 <dependency> 151 <groupId>org.apache.shiro</groupId> 152 <artifactId>shiro-spring</artifactId> 153 <version>${shiro.version}</version> 154 </dependency> 155 156 <dependency> 157 <groupId>org.apache.shiro</groupId> 158 <artifactId>shiro-ehcache</artifactId> 159 <version>${shiro.version}</version> 160 </dependency> 174 175 <!-- commons 依赖 --> 176 <dependency> 177 <groupId>org.apache.commons</groupId> 178 <artifactId>commons-lang3</artifactId> 179 </dependency> 180 181 <dependency> 182 <groupId>commons-io</groupId> 183 <artifactId>commons-io</artifactId> 184 <version>2.4</version> 185 </dependency> 186 187 <dependency> 188 <groupId>org.apache.commons</groupId> 189 <artifactId>commons-collections4</artifactId> 190 <version>4.0</version> 191 </dependency> 192 193 <dependency> 194 <groupId>commons-beanutils</groupId> 195 <artifactId>commons-beanutils</artifactId> 196 <version>1.8.3</version> 197 </dependency> 198 199 <dependency> 200 <groupId>commons-chain</groupId> 201 <artifactId>commons-chain</artifactId> 202 <version>1.2</version> 203 </dependency> 204 205 <dependency> 206 <groupId>commons-fileupload</groupId> 207 <artifactId>commons-fileupload</artifactId> 208 <version>1.3.1</version> 209 </dependency> 210 211 <dependency> 212 <groupId>org.apache.commons</groupId> 213 <artifactId>commons-math3</artifactId> 214 <version>3.3</version> 215 </dependency> 216 217 <dependency> 218 <groupId>org.apache.commons</groupId> 219 <artifactId>commons-digester3</artifactId> 220 <version>3.2</version> 221 </dependency> 222 223 <dependency> 224 <groupId>commons-net</groupId> 225 <artifactId>commons-net</artifactId> 226 <version>3.3</version> 227 </dependency> 228 229 <dependency> 230 <groupId>commons-dbutils</groupId> 231 <artifactId>commons-dbutils</artifactId> 232 <version>1.5</version> 233 </dependency> 234 235 <dependency> 236 <groupId>org.apache.commons</groupId> 237 <artifactId>commons-email</artifactId> 238 <version>1.3.3</version> 239 </dependency> 240 241 <dependency> 242 <groupId>commons-dbcp</groupId> 243 <artifactId>commons-dbcp</artifactId> 244 <version>1.4</version> 245 </dependency> 246 </dependencies> 247 248 <!-- 这个插件,可以将应用打包成一个可执行的jar包 --> 249 <build> 250 <plugins> 251 <plugin> 252 <groupId>org.springframework.boot</groupId> 253 <artifactId>spring-boot-maven-plugin</artifactId> 254 <!-- 启动主类 --> 255 <configuration> 256 <mainClass>com.MySpringBootApplication</mainClass> 257 </configuration> 258 </plugin> 259 </plugins> 260 </build> 261 262 </project>
三.项目主配置application.yml
此处配置开启Https访问,可参考我另外一篇文章,传送门:https://www.cnblogs.com/ljhblogs/p/11232163.html
在项目resource目录下创建三个yml文件,分别为
application.yml 主配置,用于选择当前环境
application-dev.yml 开发环境配置文件
application-prod.yml 生产环境配置文件
logback-spring.xml slf4j日志配置文件
application.yml
#切换项目环境-当前:dev spring: profiles: active: dev
application-dev.yml
#Spring Boot 测试环境配置
#端口
server:
port: 443 #设置https端口
http:
port: 8080 #设置http端口,访问此端口将被重定向到https端口
#开启Https协议
ssl:
key-store: classpath:mykeystore.keystore
key-store-password: 123456
key-store-type: jks
key-alias: mykeystore
#文件上传路径
file-upload-path: D:/myWorkspace/mySpringBoot/uploadPath/
#Spring配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useAffectedRows=true&serverTimezone=GMT
username: root
password: root
initialSize: 5
filters: stat
maxActive: 20
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mail:
host: smtp.163.com
username: fanshuye1304@163.com
password: fanshuye1304
freemarker:
suffix: .html
request-context-attribute: request
charset: UTF-8
aop:
proxy-target-class: true
http:
multipart:
max-file-size: 10MB
max-request-size: 10MB
devtools:
restart:
enabled: true
#mybatis配置
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
typeAliasesPackage: com.entity
#分页插件PageHelper配置
pagehelper:
helperDialect: mysql #分页插件方言选择
reasonable: true #合理化参数,设为true时pageNum<=0 时会查第一页, pageNum>pages(超过总数时),会查询最后一页
supportMethodsArguments: true
application-prod.yml
#Spring Boot 测试环境配置
#端口
server:
port: 443 #设置https端口
http:
port: 8080 #设置http端口,访问此端口将被重定向到https端口
#开启Https协议
ssl:
key-store: classpath:mykeystore.keystore
key-store-password: 123456
key-store-type: jks
key-alias: mykeystore
#文件上传路径
file-upload-path: D:/myWorkspace/mySpringBoot/uploadPath/
#Spring配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useAffectedRows=true&serverTimezone=GMT
username: root
password: root
initialSize: 5
filters: stat
maxActive: 20
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mail:
host: smtp.163.com
username: fanshuye1304@163.com
password: fanshuye1304
freemarker:
suffix: .html
request-context-attribute: request
charset: UTF-8
aop:
proxy-target-class: true
http:
multipart:
max-file-size: 10MB
max-request-size: 10MB
devtools:
restart:
enabled: true
#mybatis配置
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
typeAliasesPackage: com.entity
#分页插件PageHelper配置
pagehelper:
helperDialect: mysql #分页插件方言选择
reasonable: true #合理化参数,设为true时pageNum<=0 时会查第一页, pageNum>pages(超过总数时),会查询最后一页
supportMethodsArguments: true
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="60 seconds" debug="false"> <!--输出到控制台 ConsoleAppender--> <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender"> <!--展示格式 layout--> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </layout> </appender> <!--输出到文件 fileLog--> <appender name="fileLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!--如果只是想要 Error 级别的日志,那么需要过滤一下,默认是 info 级别的,ThresholdFilter--> <filter class="ch.qos.logback.classic.filter.ThresholdFilter" /> <File>./logger.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--文件路径,定义了日志的切分方式——把每一天的日志归档到一个文件中,以防止日志填满整个磁盘空间--> <FileNamePattern>./log/%d{yyyy-MM-dd}.log</FileNamePattern> <!--只保留最近90天的日志--> <maxHistory>10</maxHistory> <!--用来指定日志文件的上限大小,那么到了这个值,就会删除旧的日志--> <!--<totalSizeCap>1GB</totalSizeCap>--> </rollingPolicy> <!--日志输出编码格式化--> <encoder> <charset>UTF-8</charset> <pattern>%d [%thread] %-5level %logger{36} %line - %msg%n</pattern> </encoder> </appender> <!--指定最基础的日志输出级别--> <root level="DEBUG"> <!--appender将会添加到这个loger--> <appender-ref ref="consoleLog"/> <appender-ref ref="fileLog"/> </root> </configuration>
四.集成阿里数据库连接池Druid与Mybatis
对于SpringBoot默认配置来说是不需要我们额外配置数据源连接池的,因为它默认使用了HikariDataSource数据源,但因为阿里Druid提供高效功能强大的连接池及提供的SQL性能监控功能,此次我们自定义Druid数据源去替代默认的数据源连接池
- 在com包下创建一个新包config来存放相关配置类
- 在config包下创建datasource包来存放数据源相关配置类,在此包下创建DruidDBConfig配置类
- 在resource下创建mapping文件夹用来存放sql映射文件
1 package com.config.datasource; 2 3 import javax.sql.DataSource; 4 import org.springframework.beans.factory.annotation.Configurable; 5 import org.springframework.boot.context.properties.ConfigurationProperties; 6 import org.springframework.boot.web.servlet.FilterRegistrationBean; 7 import org.springframework.boot.web.servlet.ServletRegistrationBean; 8 import org.springframework.context.annotation.Bean; 9 import org.springframework.context.annotation.Primary; 10 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 11 12 import com.alibaba.druid.pool.DruidDataSource; 13 import com.alibaba.druid.support.http.StatViewServlet; 14 import com.alibaba.druid.support.http.WebStatFilter; 15 16 /** 17 * Druid数据源配置 18 * @author ljh 19 */ 20 @Configurable 21 public class DruidDBConfig { 22 23 /** 24 * 数据源 25 * @return 26 */ 27 @Bean(name = "dataSource") 28 @ConfigurationProperties(prefix = "spring.datasource") 29 public DataSource dataSource() { 30 return new DruidDataSource(); 31 } 32 33 /** 34 * 配置事务管理 35 * @return 36 */ 37 @Bean(name = "transactionManager") 38 @Primary 39 public DataSourceTransactionManager transactionManager() { 40 return new DataSourceTransactionManager(dataSource()); 41 } 42 43 /** 44 * 配置监控服务器(一个管理后台的Servlet)http://localhost:8080/druid/login.html 45 * @return 46 */ 47 @SuppressWarnings("rawtypes") 48 @ConfigurationProperties(prefix = "spring.datasource") 49 @Bean 50 public ServletRegistrationBean statViewServlet() { 51 @SuppressWarnings("unchecked") 52 ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); 53 // IP白名单 54 servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 55 // IP黑名单(共同存在时,deny优先于allow) 56 servletRegistrationBean.addInitParameter("deny","127.0.0.1"); 57 //控制台管理用户 58 servletRegistrationBean.addInitParameter("loginUsername","admin"); 59 servletRegistrationBean.addInitParameter("loginPassword","admin"); 60 //是否能够重置数据 61 servletRegistrationBean.addInitParameter("resetEnable","false"); 62 return servletRegistrationBean; 63 } 64 65 /** 66 * 配置服务过滤器 67 * @return 返回过滤器配置对象 68 */ 69 @SuppressWarnings({ "rawtypes", "unchecked" }) 70 @Bean 71 public FilterRegistrationBean webStatFilter() { 72 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); 73 // 拦截的请求 74 filterRegistrationBean.addUrlPatterns("/*"); 75 // 忽略的请求 76 filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,"); 77 return filterRegistrationBean; 78 } 79 }
五.集成Shiro
- 在com包下创建shiro包用来存放shiro相关配置
- 在shiro包下创建CustomRealm自定义类实现自定义身份认证及权限管理
1 package com.config.shiro; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.apache.shiro.SecurityUtils; 7 import org.apache.shiro.authc.AuthenticationException; 8 import org.apache.shiro.authc.AuthenticationInfo; 9 import org.apache.shiro.authc.AuthenticationToken; 10 import org.apache.shiro.authc.SimpleAuthenticationInfo; 11 import org.apache.shiro.authc.UnknownAccountException; 12 import org.apache.shiro.authc.UsernamePasswordToken; 13 import org.apache.shiro.authz.AuthorizationInfo; 14 import org.apache.shiro.authz.SimpleAuthorizationInfo; 15 import org.apache.shiro.realm.AuthorizingRealm; 16 import org.apache.shiro.subject.PrincipalCollection; 17 import org.apache.shiro.util.ByteSource; 18 import org.springframework.beans.factory.annotation.Autowired; 19 import org.springframework.util.StringUtils; 20 21 import com.dao.PermissionDao; 22 import com.entity.Permission; 23 import com.entity.Role; 24 import com.entity.User; 25 import com.service.UserRoleService; 26 import com.service.UserService; 27 28 /** 29 * 自定义Shiro身份认证和授权处理 30 * @author ljh 31 */ 32 public class CustomRealm extends AuthorizingRealm{ 33 34 @Autowired 35 private UserService userService; 36 37 @Autowired 38 private UserRoleService userRoleService; 39 40 @Autowired 41 private PermissionDao permissionDao; 42 43 /** 44 * 身份验证--登录 45 */ 46 @Override 47 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { 48 UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; 49 String userName = token.getUsername(); 50 51 User user = userService.getUserByName(userName); 52 if (null == user) { 53 throw new UnknownAccountException("此用户不存在"); 54 } 55 56 ByteSource credentialsSalt = ByteSource.Util.bytes(userName);//使用账号作为盐值 57 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt, getName()); 58 return info; 59 } 60 61 /** 62 * 身份授权--权限 63 */ 64 @Override 65 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 66 if (null == principals) { 67 return null; 68 } 69 70 // 因为非正常退出,即没有显式调用 SecurityUtils.getSubject().logout() 71 // (可能是关闭浏览器,或超时),但此时缓存依旧存在(principals),所以会自己跑到授权方法里。 72 if (!SecurityUtils.getSubject().isAuthenticated()) { 73 doClearCache(principals); 74 SecurityUtils.getSubject().logout(); 75 return null; 76 } 77 78 //获取用户 79 User user =(User) SecurityUtils.getSubject().getPrincipal(); 80 81 List<Role> roleList=userRoleService.getRoleListByUserId(user.getId()); 82 83 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); 84 85 //加入角色 86 for (Role role : roleList) { 87 info.addRole(role.getName()); 88 } 89 90 // 添加权限 91 List<Permission> permissions = permissionDao.findUserPermission(user.getId()); 92 List<String> list = new ArrayList<String>(); 93 for (Permission item: permissions) { 94 if (!StringUtils.isEmpty(item.getPermCode())) 95 list.add(item.getPermCode()); 96 } 97 info.addStringPermissions(list); 98 99 return info; 100 } 101 102 103 104 105 }
4.在shiro包下创建ShiroConfig配置类
1 package com.config.shiro; 2 3 import java.util.LinkedHashMap; 4 import java.util.Map; 5 6 import javax.servlet.Filter; 7 8 import org.apache.shiro.authc.credential.HashedCredentialsMatcher; 9 import org.apache.shiro.spring.LifecycleBeanPostProcessor; 10 import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; 11 import org.apache.shiro.spring.web.ShiroFilterFactoryBean; 12 import org.apache.shiro.web.filter.authc.LogoutFilter; 13 import org.apache.shiro.web.mgt.DefaultWebSecurityManager; 14 import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; 15 import org.springframework.beans.factory.annotation.Qualifier; 16 import org.springframework.context.annotation.Bean; 17 import org.springframework.context.annotation.Configuration; 18 import org.springframework.context.annotation.DependsOn; 19 20 /** 21 * 配置Shiro 22 * @author ljh 23 */ 24 @Configuration 25 public class ShiroConfig { 26 27 /** 28 * 配置自定义的密码比较器 29 * @return 30 */ 31 @Bean(name = "hashedCredentialsMatcher") 32 public HashedCredentialsMatcher getHashedCredentialsMatcher() { 33 HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); 34 //加密算法 35 credentialsMatcher.setHashAlgorithmName("MD5"); 36 //加密次数 37 credentialsMatcher.setHashIterations(1024); 38 credentialsMatcher.setStoredCredentialsHexEncoded(true); 39 return credentialsMatcher; 40 } 41 42 /** 43 * 配置自定义的权限登录器 44 * @param matcher 45 * @return 46 */ 47 @Bean(name="authRealm") 48 public CustomRealm authRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher) { 49 CustomRealm authRealm=new CustomRealm(); 50 authRealm.setCredentialsMatcher(matcher); 51 return authRealm; 52 } 53 54 /** 55 * 配置核心安全事务管理器 56 * @param authRealm 57 * @return 58 */ 59 @Bean(name="securityManager") 60 public DefaultWebSecurityManager securityManager(@Qualifier("authRealm") CustomRealm authRealm) { 61 DefaultWebSecurityManager manager=new DefaultWebSecurityManager(); 62 manager.setRealm(authRealm); 63 return manager; 64 } 65 66 @Bean(name="shiroFilterFactoryBean") 67 public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) { 68 69 ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); 70 shiroFilterFactoryBean.setSecurityManager(securityManager); 71 72 //配置Shiro过滤器 73 Map<String, Filter> filters = new LinkedHashMap<String, Filter>(); 74 LogoutFilter logoutFilter = new LogoutFilter(); 75 logoutFilter.setRedirectUrl("/login"); 76 filters.put("logout", logoutFilter); 77 78 //配置Shiro过滤器拦截路径 79 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); 80 81 /** 82 * anon:所有url都都可以匿名访问; 83 * authc: 需要认证才能进行访问; 84 * user:配置记住我或认证通过可以访问; 85 */ 86 87 //静态资源过滤 88 filterChainDefinitionMap.put("/css/**", "anon"); 89 filterChainDefinitionMap.put("/fonts/**", "anon"); 90 filterChainDefinitionMap.put("/img/**", "anon"); 91 filterChainDefinitionMap.put("/js/**", "anon"); 92 filterChainDefinitionMap.put("/plugins/**", "anon"); 93 94 filterChainDefinitionMap.put("/login", "anon"); 95 filterChainDefinitionMap.put("/login.html", "anon"); 96 filterChainDefinitionMap.put("/createImgCode", "anon"); 97 filterChainDefinitionMap.put("/error/", "anon"); 98 filterChainDefinitionMap.put("/logout", "logout"); 99 filterChainDefinitionMap.put("/auth", "anon"); 100 filterChainDefinitionMap.put("/static/**", "anon"); 101 filterChainDefinitionMap.put("/userHeadImgs/", "anon"); 102 filterChainDefinitionMap.put("/**", "authc"); 103 104 //登录页面 105 shiroFilterFactoryBean.setLoginUrl("/login"); 106 //登录成功后的页面 107 shiroFilterFactoryBean.setSuccessUrl("index/index"); 108 //未授权界面 109 shiroFilterFactoryBean.setUnauthorizedUrl("error/unauthorized"); 110 111 shiroFilterFactoryBean.setFilters(filters); 112 shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); 113 return shiroFilterFactoryBean; 114 } 115 116 @Bean(name = "lifecycleBeanPostProcessor") 117 public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { 118 return new LifecycleBeanPostProcessor(); 119 } 120 121 @Bean 122 @DependsOn("lifecycleBeanPostProcessor") 123 public DefaultAdvisorAutoProxyCreator getAutoProxyCreator(){ 124 DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); 125 creator.setProxyTargetClass(true); 126 return creator; 127 } 128 129 @Bean 130 public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){ 131 DefaultAdvisorAutoProxyCreator creator=new DefaultAdvisorAutoProxyCreator(); 132 creator.setProxyTargetClass(true); 133 return creator; 134 } 135 136 @Bean 137 public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") DefaultWebSecurityManager manager) { 138 AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor(); 139 advisor.setSecurityManager(manager); 140 return advisor; 141 } 142 143 }
六.配置https访问及路径相关
在config包下创建WebConfig配置类
1 package com.config.web; 2 3 import org.apache.catalina.Context; 4 import org.apache.catalina.connector.Connector; 5 import org.apache.tomcat.util.descriptor.web.SecurityCollection; 6 import org.apache.tomcat.util.descriptor.web.SecurityConstraint; 7 import org.springframework.beans.factory.annotation.Value; 8 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 9 import org.springframework.boot.web.servlet.FilterRegistrationBean; 10 import org.springframework.context.annotation.Bean; 11 import org.springframework.context.annotation.Configuration; 12 import org.springframework.web.cors.CorsConfiguration; 13 import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 14 import org.springframework.web.filter.CorsFilter; 15 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 16 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 17 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 18 19 /** 20 * web相关配置 21 * @author ljh 22 */ 23 @Configuration 24 public class WebConfig implements WebMvcConfigurer { 25 26 @Value("${server.port}") 27 private int serverPort; 28 29 @Value("${server.http.port}") 30 private int serverHttpPort; 31 32 @Value("${file-upload-path}") 33 private String fileUploadPath; 34 35 /** 36 * 配置项目默认访问页面 37 * @param registry 38 */ 39 @Override 40 public void addViewControllers(ViewControllerRegistry registry){ 41 registry.addViewController("").setViewName("login"); 42 } 43 44 /** 45 * 静态资源配置 46 */ 47 @Override 48 public void addResourceHandlers(ResourceHandlerRegistry registry) { 49 //项目静态资源映射 50 registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); 51 //服务器磁盘文件映射 52 registry.addResourceHandler("/myWorkspace/mySpringBoot/uploadPath/**").addResourceLocations("file:"+fileUploadPath); 53 } 54 55 /** 56 * 解决跨域问题 57 * @param registry 58 */ 59 @Bean 60 public FilterRegistrationBean<CorsFilter> corsFilter() { 61 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 62 CorsConfiguration config = new CorsConfiguration(); 63 config.setAllowCredentials(true); 64 // 设置你要允许的网站域名,*表示任意域名 65 config.addAllowedOrigin("*"); 66 // 表示你要允许的请求头部信息 67 config.addAllowedHeader("*"); 68 // 设置你要允许的请求方法 69 config.addAllowedMethod("GET,POST,PUT,DELETE,HEAD,OPTIONS"); 70 source.registerCorsConfiguration("/**", config); 71 FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source)); 72 // 这个顺序很重要,为避免麻烦请设置在最前 73 bean.setOrder(0); 74 return bean; 75 76 } 77 78 /** 79 * Tomcat配置Https 80 * @return 81 */ 82 @Bean 83 public TomcatServletWebServerFactory servletContainer() { 84 TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory () { 85 @Override 86 protected void postProcessContext(Context context) { 87 SecurityConstraint securityConstraint = new SecurityConstraint(); 88 securityConstraint.setUserConstraint("CONFIDENTIAL"); 89 SecurityCollection collection = new SecurityCollection(); 90 collection.addPattern("/*"); 91 securityConstraint.addCollection(collection); 92 context.addConstraint(securityConstraint); 93 } 94 }; 95 96 tomcat.addAdditionalTomcatConnectors(initiateHttpConnector()); 97 return tomcat; 98 } 99 100 /** 101 * 配置监听端口 102 */ 103 private Connector initiateHttpConnector() { 104 Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); 105 connector.setScheme("http"); 106 //Connector监听的http的端口号 107 connector.setPort(serverHttpPort); 108 connector.setSecure(false); 109 //监听到http的端口号后转向到的https的端口号 110 connector.setRedirectPort(serverPort); 111 return connector; 112 } 113 }
七.配置启动类
package com; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplicationpublic class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class, args); } }
至此SpringBoot项目的搭建已经完成