1. Spring Boot下载
Dependencies中常用的依赖:
Web,devtools,test,thymeleaf
解压,import到eclipse中
2. Spring Boot结构
基础结构分为三部分:
Src/java/main:程序开发及主程序入口
Src/java/resource:配置文件
Src/test/java:测试程序
main程序目录建议:
Application.java:框架配置,程序入口
Domain:实体类Entity
Dao:数据访问层
Service:业务逻辑层
Web:页面访问层
Common:通用类
静态文件(css,js)放到 src/java/resource/statics中
模板文件(template)放到 src/java/resource/templates中
web开发:
web开发需要在pom.xml中引入web包:
启动:
在application.java中的main方法可以启动程序,默认.
Main方法上加@SpringBootApplication
热启动:
配置热启动后,修改代码后不用重新运行项目了
若是包没有放在root package 下,可以使用扫描来加载
| @ComponentScan(basePackages=”com.dw.example”) |
|---|
或者使用bean来初始化
| @BeanPublic MyController myController(){ Return new MyController();} |
|---|
3. Spring Boot配置文件
3.1. json接口
在类上使用@RestController代替@Controller,会返回json数据.
方法上不再需要写@responseBody了.
3.2. properties配置
properties文件放在resource下或类路径的config下
服务器配置:
spring.profiles.active=application-dev.properties //配置profile环境
3.3. 引入自定义的yml
自定义一个yml文件,如:shiro.yml
| ``` loginUrl: /login/view successUrl: /index/view unauthorizedUrl: /login/view chainMap: /source/** : anon /login/** : anon /** : authc
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
定义shiro的配置类,其中PropertySourcesPlaceholderConfigurer 方法引入自定义的yml,@ConfigurationProperties把信息封装成实体
| ```
@Component @ConfigurationProperties public class ShiroProperties { private String loginUrl; private String successUrl; private String unauthorizedUrl; private Map<String, String> chainMap = new LinkedHashMap<>(); public String getLoginUrl() { return loginUrl; } public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public String getSuccessUrl() { return successUrl; } public void setSuccessUrl(String successUrl) { this.successUrl = successUrl; } public String getUnauthorizedUrl() { return unauthorizedUrl; } public void setUnauthorizedUrl(String unauthorizedUrl) { this.unauthorizedUrl = unauthorizedUrl; } public Map<String, String> getChainMap() { return chainMap; } public void setChainMap(Map<String, String> chainMap) { this.chainMap = chainMap; } @Bean public static PropertySourcesPlaceholderConfigurer properties() { Resource[] resources = new Resource[]{ new ClassPathResource( "shiro.yml" ) }; PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); yamlFactory.setResources(resources); configurer.setProperties(yamlFactory.getObject()); return configurer; } }
``` |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
自定义的yml也可以这样使用
| @Component@PropertySource(“classpath:my.yml”)Public class MyProperties{ @Value(“${name}”) String name; @Value(“${age}”) Integer age;} |
| --------------------------------------------------------------------------------------------------------------------------------------- |
或者:
| @Component@PropertySource(“classpath:my.yml”)@ConfigurationPropertiesPublic class MyProperties{ String name; Integer age;//get;set;} |
| ------------------------------------------------------------------------------------------------------------------------------------ |
3.4. properties引用
在properties中定义的变量可以通过@value引用过来.
![]()
Java中使用:
![]()
3.5. properties绑定java类
使用ConfigurationProperties(prefix=””),可以把properties中数据绑定到java类中.
![]()
3.6. log配置
在配置文件中配置(自动生效)
![]()
使用:
![]()
![]()
![]()
3.7. banner
spring启动时默认图标为spring,可以在resource下新建banner.txt来代替
![]()
3.8. favicon图标
title上的图标可以禁止显示.
![]()
禁止后可以在static文件夹下放上自己喜欢的icon(名字必须是favicon.ico)
![]()
3.9. 配置元数据依赖
| ```
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
``` |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
这个依赖的作用是提示 使用配置文件
3.10. 多个properties文件
多个properties文件加载,前缀一样
如:application-dev.properties,application-test.properties
在application.properties中设置:
| spring.profiles.active=dev |
| -------------------------- |
也可以外部使用
| Java -jar dw-demo.jar --spring.profiles.active=dev |
| -------------------------------------------------- |
# 4. thymeleaf使用
4.1. 使用thymeleaf需要引入pom包
![]()
4.2. thymeleaf格式
使用时需要在html标签中引入命名空间
![]()
4.3. 基本使用
后台添加model
![]()
前台引入
![]()
如果name存在,则dew被替换为小明;如果不存在,则显示dew.
4.4. 判断
![]()
![]()
![]()
![]()
4.5. 循环
后台添加List
![]()
前台显示
![]()
效果:
![]()
4.6. list判断npe
![]()
4.7. 选择
后台UserEntity
![]()
后台添加user
![]()
前台绑定
![]()
注意:用${user.id}和*{id}效果一样
4.8. 日期格式化
![]()
![]()
4.9. 数字格式化
后台
![]()
前台
![]()
显示
![]()
4.10. 字符串截取
后台参照4.8的number:1234.56
前台
![]()
显示
![]()
4.11. 下拉框
后台Map
![]()
前台select
![]()
4.12. script中使用model中的值
script加上标签
\
![]()
使用[[${value}]]来获取值
![]()
# 5. 开启https支持
开启https需要SSL证书支持,证书可以购买,也可以用Java生成(Java生成的证书未经过认证,会显示不安全)
Java生成证书步骤:
5.1. 用keytool生成keystore.p12
![]()
5.2. 生成的keystore.p12导入到项目的根目录中
5.3. 配置properties文件
![]()
![]()
5.4. 浏览器通过https来访问
![]()
# 6. 缓存的使用
6.1. 缓存cacheManager接口
cacheManager的实现类:
SimpleChcheManager:使用ConcurrentMap来存储
EhCacheManager:EhCache缓存
RedisCacheManager:Redis缓存
缓存类型:
@Cacheable:有数据,则返回;没有数据,则缓存。
@CachePut:把返回值放到缓存中。
@CacheEvict:将数据从缓存中删除。
缓存值:
Value:缓存的名称
Key:缓存的建
存储以value+key的形式,如果不指定key,系统会随机生成一个key,所有最好指定key,以便清除的时候使用
6.2. 系统默认使用SimpleChcheManager来缓存数据
引入pom依赖包
| ```
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
``` |
| ---------------------------------------------------------------------------------------------------------------------------------------------- |
开启缓存
![]()
使用缓存
![]()
| ```
@Cacheable(value = "menu" ,key = "'list'" ) public List<SysMenuEntity> getSysMenuList() { return null; }
``` |
| --------------------------------------------------------------------------------------------------------------------------- |
注:缓存在controller,service,dao层都可以使用。
清除多个缓存
注:清除缓存时一定要指定key,不然系统会随机生成一个key
| ```
@Caching(evict = { @CacheEvict(value = "menu" ,key= "'tree'" ), @CacheEvict(value = "menu" ,key= "'list'" ) }) public boolean delete(int id) { int delete = sysMenuDao.delete(id); return delete > 0 ? true : false; }
``` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
6.3. Redis的使用
注意:springboot2.x中的redis连接方式换成了Lettuce
使用前引入pom包(删除sprint-boot-starter-chche依赖)
![]()
参数配置
![]()
使用和SimpleCacheManager一样。
注:引入redis的pom依赖后,就可以使用redisTemplate了
![]()
数据访问方法:
opsForValue():操作简单属性
opsForList():操作集合
opsForSet():操作set
opsForZSet():操作有序数据
opsForHash():操作hashMap
# 7. websocket使用
websocket建立在tcp之上,端口与http端口一样(80和443),websocket的目的是为了让客户端和服务器互相推送,弥补http协议只能由客户端发起的不足.
7.1. 引入pom依赖
![]()
7.2. 增加endpoint配置信息
![]()
7.3. 编写websocket服务端
![]()
Websokect服务端有4个方法:
onOpen:连接后触发
onClose:断开后触发
onMessage():收到消息后触发
onError():发生错误时触发
![]()
![]()
![]()
7.4. 编写html客户端
初始化websocket()
![]()
注:如果连接http,则使用ws://
如果连接https,则使用wss://
初始化后自动连接后台服务
连接监听:
![]()
关闭监听:
![]()
接收消息监听:
![]()
发送消息:
![]()
# 8. 集成Mybatis
1. 添加pom依赖包
添加mysql依赖:(不添加version会默认最新的)
| ```
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
``` |
| ---------------------------------------------------------------------------------------------------------------------- |
添加mybatis依赖:(一定要添加version)
| ```
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
``` |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2. 修改配置文件
数据库设置
| ```
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/demo username: root password: root
``` |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
Mybatis别名(配置别名后,在xml文件中就不用再写全路径了)
![]()
配置xml路径
![]()
#驼峰命名法,这样,resultMap就可以省略掉
mybatis.configuration.map-underscore-to-camel-case=true
3. 在MyBootApplication上开启mapper扫描
![]()
4. 编写dao层接口
可以在接口上直接写语句
语句分为增,删,改,查 @Insert,@Delete,@Update,@Select
返回类型可以用@Results定义
查询
![]()
新增
![]()
修改
![]()
删除
![]()
5. 编写mapper.xml
![]()
| ```
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.didispace.chapter36.mapper.UserMapper"> <select id="findByName" resultType="com.didispace.chapter36.entity.User"> SELECT * FROM USER WHERE NAME = #{name} </select> <insert id="insert"> INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age}) </insert> </mapper>
``` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
这里的mapper与com.example.MyBoot.dao.SysUserDao中的getUserList对应
![]()
6. PageHelper的使用
引入pom依赖包
![]()
增加配置信息:
| ```
pagehelper.helper-dialect=mysql pagehelper.params=count=countSql pagehelper.reasonable=false pagehelper.support-methods-arguments=true
``` |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- |
其中reasonable是分页合理化,为true时,pageNum<0会查询第一页,pageNum>最后一页,会查询最后一页
Support-methods-arguments会从查询参数中找到pagehelper.params字段的值.
查询之前使用PageHelper(PageHelper只对第一个查询命令起作用)
![]()
第一个参数是页数,第二个参数是每页条数。
7. 通用mapper的使用
通用mapper会生成增删改查和example的操作,减少90%的代码
| ```
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency>
``` |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
增加配置信息:
| ```
mapper.identity=MYSQL mapper.mappers=tk.mybatis.mapper.common.BaseMapper
设置 insert 和 update 中,是否判断字符串类型!='' mapper.not-empty=true # 枚举按简单类型处理 mapper.enum-as-simple-type=true
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
其中mapper.enum-as-simple-type 是处理枚举Enum的
Mapper.not-empty是处理insert和update中的!=’’的
使用:
在实体类上加@Table(name=”user”)
在id上加:
@Id 主键
@GeneratedValue(strategy=GeneratedType.IDENTY)(自动写会自增主键)
@Transient:忽略此字段
@Column(name=”card_no”):对应字段
在mapper中extend BaseMapper<User>
# 9. 使用druid连接池
1. 引入pom依赖包(要加版本号)
| ```
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency>
org.springframework.boot spring-boot-starter-actuator
``` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
2. properties文件配置
配置druid连接池
| ```
spring.datasource.druid.url=jdbc:mysql://localhost:3306/test spring.datasource.druid.username=root spring.datasource.druid.password= spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
``` ```
spring.datasource.druid.initialSize=10 spring.datasource.druid.maxActive=20 spring.datasource.druid.maxWait=60000 spring.datasource.druid.minIdle=1 spring.datasource.druid.timeBetweenEvictionRunsMillis=60000 spring.datasource.druid.minEvictableIdleTimeMillis=300000 spring.datasource.druid.testWhileIdle=true spring.datasource.druid.testOnBorrow=true spring.datasource.druid.testOnReturn=false spring.datasource.druid.poolPreparedStatements=true spring.datasource.druid.maxOpenPreparedStatements=20 spring.datasource.druid.validationQuery=SELECT 1 spring.datasource.druid.validation-query-timeout=500 spring.datasource.druid.filters=stat,wall
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
配置监控
| | ```
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=true spring.datasource.druid.stat-view-servlet.login-username=admin spring.datasource.druid.stat-view-servlet.login-password=admin
``` |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
页面访问:
<http://127.0.0.1/druid>
# 10.事务@Transactional
事务@Transactional在service层开启,开启后,如果中间出现错误,sql对应的事务操作会回滚,然后抛出运行时异常,controller捕捉异常并进行处理。
方法上加上@Transactional即可
![]()
事务的属性:
1. propagation传播生命周期
默认:required
没有事务,则新建事务;有事务,则加入事务。遇到错误,整个事务都要回滚。
Required_new
新建事务。遇到错误,只有本方法中回滚。
Supports
有事务,则加入事务;没有事务,则不用事务。
Not_supports
不管有没有事务,都不在事务中执行。
Nested
以子事务的形式执行(相当于建立还原点savepoint)。
Never
不在事务中执行,如果有事务,则抛出异常。
Mandatory
强制在事务中执行,如果没有事务,则抛出异常。
2. 隔离性isolation
3. 隔离级别:
Read_uncommited:可以读取未提交的事务。
Read_commited:只能读取已提交的事务。
Repeatable_read:A读取时,B不能修改。
4. @Transactional可以注解在方法上,也可以注解在类上。
注解在类上,表明,类中的所有public方法都开启了事务。
# 11.打包发布
打开cmd,进入程序的根目录中
![]()
执行打包操作
![]()
会在根目录>target中生成jar包
执行jar包
![]()
在浏览器中查看
# 12. 自定义错误信息
1.自定义错误信息,解决页面找不到的情况
代码如下
| ```
@RestController public class MyErrorController implements ErrorController { @Override public String getErrorPath() { return null; } @RequestMapping( "error" ) public Message errorHandler(HttpServletRequest request){ Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if(status != null){ int statusCode = Integer.parseInt(status.toString()); return new Message(statusCode); } return new Message(-1); } }
``` |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2.定义全局异常,实现@ControllerAdvice注解
| ```
@RestControllerAdvice public class MyExceptionHandler { @ExceptionHandler(value = Exception.class) public Message myExceptionHandler(Exception e){ return new Message(0, e.getMessage()); } }
``` |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
也可以使用ControllerAdvice返回页面信息
# 13. shiro的使用
Shiro分为认证和授权:
核心组件为:
Subject:主题(账号)
SecurityManager:管理器(管理Subject)
Realm:连接器(连接数据库,查找用户和权限)
1. 引入shiro的jar包
| ```
<dependency>
org.apache.shiro
<artifactId>shiro-spring-boot-web-starter</artifactId>
1.4.2
</dependency>
``` |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2. 编写realm类
| ```
public class UserRealm extends AuthorizingRealm { @Autowired SysUserRoleService sysUserRoleService; @Autowired SysUserService sysUserService;
@Autowired SysUserPermService sysUserPermService; /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // 获取用户(包括角色和权限) SysUserEntity user = (SysUserEntity) principalCollection.getPrimaryPrincipal(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Info.setRols(roles )
Info.setStringPermissions(perms); return info; } /** * 认证 * @param authenticationToken * @return */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) { // 获取token UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; // 获取用户信息(包括权限和角色) SysUserEntity sysUserEntity =sysUserService.getSysUserByAccount(token.getUsername()); if(sysUserEntity == null){ return null; } return new SimpleAuthenticationInfo(sysUserEntity,token.getPassword(),getName()); } }
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
3. 编写shiro的config类
| ```
@Configuration public class ShiroConfig {
// 注入自定义的realm,告诉shiro如何获取用户信息来做登录或权限控制
@Bean
public Realm realm() {
return new CustomRealm();
}
/** * url 配置 * @return */ @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition (){
DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition ();
chain.addPathDefinition(“/static/**”,”anon”);
chain.addPathDefinition(“/admin/**”,”authc,roles[admin]”);
chain.addPathDefinition(“/user/**”,”authc,perms[user:read]”);
chain.addPathDefinition(“/**”,”authc”);
Return chain;
}
/** * 启动代理(解决与Spring AOP一起使用的bug) * @return */ @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){ DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); creator.setProxyTargetClass(true); return creator; } }
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
4. 登陆验证
| ```
@RequestMapping( "/check" ) public String loginCheck(String account,String password){ System.out.println( "to check" ); Subject user = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(account, password); try { user.login(token); }catch (AuthenticationException e){ return "/index" ; } return "index" ; }
``` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
5. 退出
| ```
@RequestMapping( "/logout" ) public String logout(){ SecurityUtils.getSubject().logout(); return "login" ; }
``` |
| ---------------------------------------------------------------------------------------------------------------------------------- |
6. 权限使用
| ```
@RequestMapping( "/user" ) @ResponseBody @RequiresPermissions( " 权限2" ) public String getUser(){ return "user" ; }
``` |
| --------------------------------------------------------------------------------------------------------------------------------------- |
验证包括:
@RequiresGuest:只有游客可以访问
@RequiresAuthentication:登录后才能访问
@RequiresUser:已登录的用户可以访问
@RequiresRoles:特定角色才可访问
@RequiresPermissions:特定权限才可访问
过滤器包括:
Anon:随意访问
Authc:验证后访问
Logout:登出
Perms:需要权限
Port:指定端口登录
Roles:指定角色登录
Ssl:需要ssl才能登录
User:已登录才能访问
Shiro异常包括:
ShiroException:授权失败
UnauthenticatedException:未登录
UnauthorizedException:未授权
properties配置:
| #允许cookie(默认:true)shiro.sessionManager.sessionIdCookieEnabled=true#允许放到url中(默认:true)shiro.sessionManager.sessionIdUrlRewritingEnabled=true#开启验证(默认开启)shiro.web.enabled=true#成功跳转(默认:/)shiro.successUrl=/index#未登录跳转(默认:login.jsp)shiro.loginUrl=/login#未授权跳转路径(默认:null)shiro.unauthorizedUrl=/unauthorizedurl |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
Shiro全部配置:
| ```
shiro:
web:
## 开启shiro web自动化配置,默认开启
enabled: true
loginUrl: /login.jsp
successUrl: /
## 必须要配置为授权的url,否则在无权限的情况下,会找不到未授权url,导致找不到安全管理器(SecurityManager)
unauthorizedUrl: null
## session管理方式,true使用shiro提供的session管理,false则使用servlet提供的session管理
userNativeSessionManager: false
## 会话管理
sessionManager:
sessionIdCookieEnabled: true
sessionIdUrlRewritingEnabled: true
deleteInvalidSessions: true
cookie:
name: JSESSIONID
maxAge: -1
domain: null
path: null
secure: false
## 记住我管理
rememberMeManager:
cookie:
name: rememberMe
## 默认一年
maxAge: 60 * 60 * 24 * 365
domain: null
path: null
secure: false
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
# 14. Spring Boot多模块
1. 建立一个springboot工程,删除src目录
2. 修改pom.xml文件
Packaging方式变为pom
| ```
<packaging>pom</packaging>
``` |
| ---------------------------------- |
增加子模块
| ```
<modules> <module>controller</module> <module>entity</module> <module>service</module> </modules>
``` |
| --------------------------------------------------------------------------------------------------------------------------- |
plugins中,关闭单元测试
| ```
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skipTests>true</skipTests> <!-- 默认关掉单元测试 --> </configuration> </plugin>
``` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3. 在工程上右键new->Module
修改子模块的pom.xml文件
Parent修改为母模块(所以的子模块都要修改)
| ```
<parent> <groupId>com.example</groupId> <artifactId>multi</artifactId> <version>0.0.1-SNAPSHOT</version> </parent>
``` |
| -------------------------------------------------------------------------------------------------------------------------------------------- |
4. 在web模块的 pom.xml中增加maven打包配置
| ```
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!-- 指定该Main Class为全局的唯一入口 --> <mainClass>com.example.ControllerApplication</mainClass> <layout>ZIP</layout> </configuration> <executions> <execution> <goals> <goal>repackage</goal> <!-- 可以把依赖的包都打包到生成的Jar包中--> </goals> </execution> </executions> </plugin> </plugins> </build>
``` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
注:web模块中的ControllerApplication要提到com.example下,不然扫描不到其他层
5. 打包后的web模块,可以直接使用了
# 15. 实体类
15.1. 实体类需要写get,set方法,引入jar包,可以省略
| ```
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
``` |
| ------------------------------------------------------------------------------------------------------------------ |
| ```
@Data public class User { private Long id; private String name; private Integer age; }
``` |
| ----------------------------------------------------------------------------------------------------------------- |
15.2. @RequestMapping
Spring boot 2.x 新增 @GetMapping 和 @PostMapping
@PutMapping:更新请求
@DeleteMapping:删除请求
15.3. 对json参数的绑定
以前用@ModelAttribute,现在用@RequestBody
url中带的参数用@PathVariable
# 16. 字段校验
| | `@NotNull` | **限制必须不为null** |
| --------------------------- | ------------------------------------------------------------------------------- |
| `@NotEmpty` | **验证注解的元素值不为 null 且不为空(字符串长度不为0、集合大小不为0)** |
| `@NotBlank` | **验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格** |
| `@Pattern(value)` | **限制必须符合指定的正则表达式** |
| `@Size(max,min)` | **限制字符长度必须在 min 到 max 之间(也可以用在集合上)** |
| `@Email` | **验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式** |
| `@Max(value)` | **限制必须为一个不大于指定值的数字** |
| `@Min(value)` | **限制必须为一个不小于指定值的数字** |
| `@DecimalMax(value)` | **限制必须为一个不大于指定值的数字** |
| `@DecimalMin(value)` | **限制必须为一个不小于指定值的数字** |
| `@Null` | **限制只能为null(很少用)** |
| `@AssertFalse` | **限制必须为false (很少用)** |
| `@AssertTrue` | **限制必须为true (很少用)** |
| `@Past` | **限制必须是一个过去的日期** |
| `@Future` | **限制必须是一个将来的日期** |
| `@Digits(integer,fraction)` | **限制必须为一个小数,且整数部分的位数不能超过 integer,小数部分的位数不能超过 fraction (很少用)** | | |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - |
![]()
在实体类上加上标注:
| @NotBlank(message=”姓名不能为空”)@Length(min=2,max=5,message=”长度{min}-{max}”)Private String name; |
| ------------------------------------------------------------------------------------------- |
在路径中,标记:
| Public String getUser(@Valid @RequestBody User user){ Return new User();} |
| ------------------------------------------------------------------------- |
可以标记在参数上,也可以标记在类上 @Valid
可以自定义校验规则
验证组:group
建立一个验证组
| public class group{ Public interface update{} Public interface default{}} |
| --------------------------------------------------------------------------- |
实体类中对字段进行归属:
| @NotNull(message=”id不能为空”,groups=Group.update.class)Private integer id; |
| ----------------------------------------------------------------------- |
在验证的时候,标注哪个需要验证
| Public String update(@Valid(value = {Group.update.class,group.default.class}) User user){} |
| ------------------------------------------------------------------------------------------ |
# 17. 日志的配置
默认日志是logback
# 18. 维护文档
文档使用Swagger
# 19. 健康检测工具
Actuator可以监控springboot的安全状态.
Actuator可以和springboot-admin配合使用.
# 20. 定时任务
springboot自带定时任务,是简单的quertz
在方法上直接加@Scheduled(cron=””) @Async
在Application: @EnableScheduling @EnableAsync
# 21. 文件上传
默认情况,文件上传无需配置.但是配置了利于对问题的定位
| ```
# 禁用 thymeleaf 缓存 spring.thymeleaf.cache=false # 是否支持批量上传 (默认值 true) spring.servlet.multipart.enabled=true # 上传文件的临时目录 (一般情况下不用特意修改) spring.servlet.multipart.location= # 上传文件最大为 1M (默认值 1M 根据自身业务自行控制即可) spring.servlet.multipart.max-file-size=1048576 # 上传请求最大为 10M(默认值10M 根据自身业务自行控制即可) spring.servlet.multipart.max-request-size=10485760 # 文件大小阈值,当大于这个阈值时将写入到磁盘,否则存在内存中,(默认值0 一般情况下不用特意修改) spring.servlet.multipart.file-size-threshold=0 # 判断是否要延迟解析文件(相当于懒加载,一般情况下不用特意修改) spring.servlet.multipart.resolve-lazily=false
``` |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
后端接受:
@RequestParam(“file”) MultipartFile file 多个文件就是:MultipartFile[] files
File.getContentType();//类型
File.getSize();//大小
File.getFileName();//名称
File.transferTo();//保存文件
# 22. Spring Security
Spring boot 可以使用Spring Security验证.
两个重要概念:authentication(认证),authorization(授权)
22.1. Authentication:认证
认证信息接口集成了principal类,方法包括:
getAuthorities():获取权限信息
getCredentials():获取用户凭证(比如:密码)
getDetails():获取用户详情(ip,session等)
GetPrincipal():获取用户身份(比如,我们存储的User类)
22.2. AuthenticationManager
认证管理器,负责验证信息.认证成功后,会返回Authentication信息.
常用实现类是:ProviderManager
22.3. UserDetailsService 用户service
加载用户信息,需要自己实现.
22.4. UserDetails 用户实体
22.5. 存储用户信息
一般包括:
getAuthorities():权限集合
getPassword():密码
getUserName():用户名
isAccountNonExpired():是否过期
IsAccountNonLocked():是否锁定
IsCredentialNonExpired():用户凭证是否过期
isEnabled():是否可用
22.6. 如何使用:
首先,引入security包:
| ```
<dependency>
org.springframework.boot
<artifactId>spring-boot-starter-security</artifactId>
``` |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
然后,配置security config信息
| @configuration@EnableWebSecurityPublic class SecurityConfig extends WebSecurityConfigurerAdapter{ } |
|---|