标签:生成 release result get query example 定向 org arrays
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
ctrl+shift+alt+/,点击Registry
File -- Settings -- Build, Execution, Deployment -- Compiler
Edit Configurations
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
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;
}
}
<?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.example.demo.mapper.UserMapper">
<resultMap id="userMap" type="User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
</resultMap>
<select id="getUserByID" resultMap="userMap" parameterType="INTEGER">
select * from user where id = #{id}
</select>
</mapper>
基本配置
# 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)
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
使用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) +
‘}‘;
}
}
}
//所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
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依赖,否则可能报错
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
*/
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
全局异常处理
@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);
}
}
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
//所需依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
// 案列
// controller
IPage<Tag> page = tagService.tagSelectByPagination(current, size, new Tag());
List<Tag> records = page.getRecords()
// mapper
@Select("select * from tb_tag")
List<Tag> tagSelectByPagination(IPage<Tag> iPage,Tag tag);
// service
IPage<Tag> tagSelectByPagination(int current,int size,Tag tag);
` // Impl
@Override
public IPage<Tag> tagSelectByPagination(int current, int size, Tag tag) {
IPage<Tag> page = new Page<>(current, size);
page.setRecords(tagMapper.tagSelectByPagination(page, tag));
return page;
}
静态资源文件夹路径即CLASSPATH_RESOURCE_LOCATIONS
# 配置静态资源文件夹,springboot默认配置的会失效
spring:
resources:
static-locations: classpath:/myStaticLocations01/,classpath:/myStaticLocations02/
静态资源文件夹下的所有index.html
静态资源文件夹下的favicon.ico
@Mapper的作用
可以注解在类或者方法上,注解在方法上一定会抛出异常
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
对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
标签:生成 release result get query example 定向 org arrays
原文地址:https://www.cnblogs.com/kwdlh/p/13174749.html