SpringBoot
2021-05-09 01:30
标签:生成 release result get query example 定向 org arrays
常用配置
热部署
- 配置依赖
org.springframework.boot
spring-boot-devtools
true
- IDEA设置
ctrl+shift+alt+/,点击Registry
File -- Settings -- Build, Execution, Deployment -- Compiler
Edit Configurations
application.yml
spring:
profiles:
active: dev
server:
port: 8082
spring:
datasource:
username: root
password: 12345678
url: jdbc:mysql://localhost:3306/myvue?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*Mapping.xml
type-aliases-package: com.example.demo.entity
# 打印sql
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
拓展SpringMvc
配置类
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("test");
}
//配置拦截器方式一
@AutoWried
private MyInterceptor myInterceptor
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(myInterceptor)
}
//配置拦截器方式二
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
}
自定义拦截器
//方式一
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getSession().getAttribute("user") == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
}
//方式二
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (request.getSession().getAttribute("user") == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
}
整合mybatis框架
日志功能
基本配置
# application.yml
logging:
config: classpath:logback-spring.xml
level:
root: info
com.example.demo: info
file: log/blog-dev.log
文件路径:resources/logback-spring.xml logback-spring.xml
//使用@Slf4j代替Logger logger=LoggerFactory.getLogger(UserController.class)
org.projectlombok
lombok
true
使用aop
@Comoponent
@Aspect
@Slf4j
public void logAspect(JoinPoint joinPoint){
@Pointcut(execution("* com.example.demo.controller..*.*(..)"))
public void controllerLog(){}
@Before("controllerLog()")
public void before(){
ServletRequestAttribute attributes =(ServletRequest) RequestContextHolder.getRequestAttributes();
HttpServlterRequest request = attributes.getRequest();
String url = request.getRequestURL.toString();
String ip = request.getRomotoAddr();
String method = joinPoint.getSignature.getDeclaringTypeName()+"."+joinPoint.getSignature.getName();
Object[] args = joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url,ip,method,args)
log.info("request {}",requestLog)
}
@After("controllerLog()")
public void after(){}
@AfterReturning(pointcut="controllerLog()",returning="result")
public void afterReturning(Object result){
log.info("result: {}",result)
}
@Afterthrowing("controllerLog()")
public void afterThrowing(){
}
//内部类
private class RequestLog {
private String url;
private String ip;
private String classMethod;
private Object[] args;
public RequestLog(String url, String ip, String classMethod, Object[] args) {
this.url = url;
this.ip = ip;
this.classMethod = classMethod;
this.args = args;
}
@Override
public String toString() {
return "{" +
"url=‘" + url + ‘\‘‘ +
", ip=‘" + ip + ‘\‘‘ +
", classMethod=‘" + classMethod + ‘\‘‘ +
", args=" + Arrays.toString(args) +
‘}‘;
}
}
}
//所需依赖
org.springframework.boot
spring-boot-starter-aop
Druid连接池
com.alibaba
druid
1.1.21
application.yml配置
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
username: root
password: 12345678
type: com.alibaba.druid.pool.DruidDataSource
# 连接池的配置信息
# 初始化大小,最小等待连接数量,最大等待连接数量,最大连接数
initialSize: 1
minIdle: 1
# 已废弃
# maxIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,‘wall‘用于防火墙
filters: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
# spring.datasource.useGlobalDataSourceStat=true
配置类
@Configuration
public class DruidConfig{
@ConfigurationProperties(perfix="spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}
/*
需要log4j依赖,否则可能报错
log4j
log4j
1.2.12
*/
pom.xml
UTF-8 UTF-8 11 3.0.11.RELEASE 2.0.4
异常处理
全局异常处理
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
log.error("Request URL : {},Exception : {}", request.getRequestURL(), e);
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("url", request.getRequestURL());
modelAndView.addObject("exception", e);
modelAndView.setViewName("error/error");
return modelAndView;
}
}
手动抛出异常
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
private static final long serialVersionUID = 6501798322019502342L;
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
mybatis-plus分页配置
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
//所需依赖
com.baomidou
mybatis-plus-boot-starter
3.3.1
// 案列
// controller
IPage page = tagService.tagSelectByPagination(current, size, new Tag());
List records = page.getRecords()
// mapper
@Select("select * from tb_tag")
List tagSelectByPagination(IPage iPage,Tag tag);
// service
IPage tagSelectByPagination(int current,int size,Tag tag);
` // Impl
@Override
public IPage tagSelectByPagination(int current, int size, Tag tag) {
IPage page = new Page(current, size);
page.setRecords(tagMapper.tagSelectByPagination(page, tag));
return page;
}
静态资源映射
静态资源文件夹
静态资源文件夹路径即CLASSPATH_RESOURCE_LOCATIONS
- "classpath:/WEB-INF/resources/"
- "classpath:/resources/"
- "classpath:/static/"
- "classpath:/public/"
# 配置静态资源文件夹,springboot默认配置的会失效
spring:
resources:
static-locations: classpath:/myStaticLocations01/,classpath:/myStaticLocations02/
欢迎页
静态资源文件夹下的所有index.html
图标
静态资源文件夹下的favicon.ico
常用注解
@Mapper
@Mapper的作用
- 为了把mapper这个DAO交给Spring管理
- 为了不再写mapper映射文件
- 为了给mapper接口 自动根据一个添加@Mapper注解的接口生成一个实现类
@ResponseStatus
可以注解在类或者方法上,注解在方法上一定会抛出异常
其它知识
介绍
Maven中groupId和artifactId的含义
groupId和artifactId被统称为“坐标”是为了保证项目唯一性而提出的,如果你要把你项目弄到maven仓库去,你想要找到你的项目就必须根据这两个id去查找。
- groupId是项目组织的唯一标识符
- artifactId就是项目的唯一标识符
请求转发和重定向区别
请求转发 | 重定向 |
---|---|
浏览器发出一次请求,获取一次响应 | 浏览器发出2次请求,获取2次请求 |
浏览器地址栏未发生变化,仍是第1次发出的请求 | 浏览器地址栏发生变化,仍是第2次发出的请求 |
也称为服务器内跳转 | 也称为服务器外跳转 |
资源2中可以获取到用户提交请求中的数据 | 资源2中不可以获取到用户提交请求中的数据,但可以获取到第2次由浏览器自动发出的请求中携带的数据 |
在请求转发目录可以将请求转发到WEB-INF目录下的资源 | 不可以将请求转发到WEB-INF目录下的资源 |
只能将请求转发到WEB应用的内部资源 |
注解
@EnableWebMvc
全面接管springmvc,springboot对springmvc的默认配置全部失效
@Data
@Data相当于@Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode这5个注解的合集。(需要lombok插件)
@EqualsAndHashCode(callSuper=true)
开发一般都会同时加上@Data,@EqualsAndHashCode(callSuper=true)这两个注解
配置
定制banner
文件路径:resources/banner.txt
在线生成banneruser
mysql
对id重新排序
ALTER TABLE user DROP id;
ALTER TABLE user ADD id INT NOT NULL;
ALTER TABLE user MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(id);
SELECT * FROM user ORDER BY id
id自增1
# 插入前执行
ALTER TBALE user AUTO_INCREMENT = 1
SpringBoot
标签:生成 release result get query example 定向 org arrays
原文地址:https://www.cnblogs.com/kwdlh/p/13174749.html
上一篇:python之面向对象4
下一篇:文件上传