框架搭建
引入Spring Boot模块
- web
- Thymeleaf
- JPA
- MySQL
- Aspects(未找到这个模块,是否已经集成?)
- DevTools
application.yml配置
完整配置文件及可能出现的问题如下(后续可能根据需要调整):
# 首先开发工具(IDEA)编码设置为utf-8,否则springboot在读取配置文件时可能出现异常
spring:
# 激活的环境配置
profiles:
active: dev
# 配置thymeleaf(新版本已默认,无需配置)
# thymeleaf:
# mode: HTML
# 配置数据库方言
jpa:
database-platform: org.hibernate.dialect.MySQLDialect
---
# 开发环境配置,也可拆分后放在application-dev.yml文件中
spring:
profiles: dev
# 数据库连接配置
# com.mysql.jdbc.Driver已过时,用com.mysql.cj.jdbc.Driver
# 这里连接串上的时区设置一定要有
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
# JPA配置,项目启动时更新表结构
jpa:
hibernate:
ddl-auto: update
show-sql: true
# 日志配置
logging:
level:
root: info
com.nianhen: debug
file:
# path 和 name 同一配置下只有一个生效
# path: /log/
name: ./log/blog-dev.log
# 服务端口配置
server:
port: 8080
---
# 生产环境的配置
spring:
profiles: prod
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
jpa:
hibernate:
ddl-auto: none
show-sql: false
logging:
level:
root: warn
com.nianhen: info
file:
name: ./log/blog.log
server:
port: 80
异常处理
定义错误页面
- 404
- 500
- error
全局异常处理
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author nianhen
* @2020/4/515:18
* 自定义异常类
* 处理目标页面不存在等场景,将状态码设为HttpStatus.NOT_FOUND(404)
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
package com.nianhen.blog.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* @author nianhen
* @2020/4/514:55
* 全局异常处理类
* 若异常类上有指定错误响应状态码,将异常直接抛出,交由springboot处理,否则转发到错误页面
*/
@ControllerAdvice
public class ControllerExceprionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
logger.error("Request URL : {}, Exception : {}", request.getRequestURL(), e);
if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
ModelAndView mv = new ModelAndView();
mv.addObject("url", request.getRequestURL());
mv.addObject("exception", e);
mv.setViewName("error/error");
return mv;
}
}
日志处理
记录内容
- 请求url
- 访问者ip
- 调用方法
- 请求参数
- 响应内容
记录方式
package com.nianhen.blog.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* @author nianhen
* @2020/4/516:06
* 日志切面类
* 将com.nianhen.blog.web包下所有方法设为连接点编写切面增强方法
* 通过RequestContextHolder获取所需数据
*/
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* com.nianhen.blog.web.*.*(..))")
public void log() {}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String url = request.getRequestURL().toString();
String ip = request.getRemoteAddr();
String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
Object[] args= joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
logger.info("RequestLog: {}", requestLog);
}
@After("log()")
public void doAfter() {
}
@AfterReturning(returning = "result", pointcut = "log()")
public void doAfterRetrun(Object result) {
logger.info("Result: {}", result);
}
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) +
'}';
}
}
}
页面处理
静态页面导入Project
注意本地静态资源文件的引用,需要适配thymeleaf模板。如:
<!-- 本地样式文件 th:href -->
<link rel="stylesheet" href="../static/css/mystyle.css" th:href="@{/css/mystyle.css}">
<!-- 本地图片文件 th:src -->
<img src="../static/images/wechat.jpg" th:src="@{/images/wechat.jpg}" class="ui rounded image qr-code">
thymeleaf布局
抽出公共代码,方便修改。(模块化思想)
- 定义fragment
- 使用fragment布局
错误页面优化
引用fragment,同时编辑用户友好的错误信息。