1. 程式人生 > 實用技巧 >部落格開發:框架搭建

部落格開發:框架搭建

部落格開發:框架搭建

一.使用idea快速搭建框架

匯入mybatis-plus依賴

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
 </dependency>

二.配置配置檔案

配置yml檔案

application.yml

spring:
  thymeleaf:
    mode: HTML
  profiles:
    active: pro
mybatis
-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

application-dev.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/myblog?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 13476110270dwx
logging:
  level:
    root: info
    com.myblog.demo: debug
  file:
    name: log
/blog-dev.log

application-pro.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/myblog?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 13476110270dwx

logging:
  level:
    root: warn
    com.myblog.demo: info
  file:
    name: log
/blog-pro.log

並在resources資料夾下新增logback-spring.xml檔案對日誌進行配置

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!--包含Spring boot對logback日誌的預設配置-->
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />

    <!--重寫了Spring Boot框架 org/springframework/boot/logging/logback/file-appender.xml 配置-->
    <appender name="TIME_FILE"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i</fileNamePattern>
            <!--保留歷史日誌一個月的時間-->
            <maxHistory>30</maxHistory>
            <!--
            Spring Boot預設情況下,日誌檔案10M時,會切分日誌檔案,這樣設定日誌檔案會在100M時切分日誌
            -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>

        </rollingPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="TIME_FILE" />
    </root>

</configuration>
        <!--
            1、繼承Spring boot logback設定(可以在appliaction.yml或者application.properties設定logging.*屬性)
            2、重寫了預設配置,設定日誌檔案大小在10MB時,按日期切分日誌
        -->

三.異常處理

對404,500,error異常頁面進行處理,錯誤頁面的檔名稱必須固定:

  • 404.html:瀏覽器錯誤,資源找不到
  • 500.html:服務端錯誤
  • error.html:自定義錯誤

全域性異常處理

404和500的錯誤頁面,SpringBoot可以根據頁面的命名方式找到對應檔案,自定義的錯誤就需要自定義攔截器來攔截異常資訊並返回給error頁面,建立異常攔截器,當異常標識了狀態碼時就不攔截,沒標識狀態碼就攔截

@ControllerAdvice//攔截所有帶Controller的控制器
public class ControllerExceptionHandler {
    //    將異常記錄到日誌
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
        // 記錄異常資訊:請求的URL,異常資訊
        logger.error("Requst URL : {},Exception : {}", request.getRequestURL(),e);

        // 當標識了狀態碼的時候就不攔截
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        //    將記錄的異常資訊返回到error頁面
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}

資源找不到異常處理

資源找不到異常也有跳轉到404頁面,自定義一個異常類給其指定狀態碼就不會被攔截,建立資源找不到異常類

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
    //繼承RuntimeException的建構函式
    public NotFoundException(){}
    public NotFoundException(String message){
        super(message);
    }
    public NotFoundException(String message,Throwable cause){
        super(message,cause);
    }
}