个人博客开发记录-项目的构建-1

项目构建

1. 创建一个springboot项目

导入thymeleaf,web,mysql,JDBC API的依赖以及devtools热部署工具

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

2. 配置application.yml和dev(开发)还有pro(生产)

applicaion.yml
spring:
  thymeleaf:
    mode: HTML
  profiles:
    active: dev
---
application-dev.yml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8
    username: root
    password: ??????

mybatis:
  type-aliases-package: com.sli.entity
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

logging:
  level:
    root: info
    com.sli: debug
  file:
    path: log/
    name: BLOG-DEV.log
---
application-pro.yml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8
    username: root
    password: ???????

mybatis:
  type-aliases-package: com.sli.entity
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

logging:
  level:
    root: warn
    com.sli: info
  file:
    path: /log
    name: BLOG-PRO.log
server:
  port: 8081

3. 创建异常页面(404 500 等)

  1. 在templates中新建一个error文件夹以及index.html
    index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
  <h1>首页</h1>
</body>
</html>
  1. error中新建404.html,500html,error.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404</title>
</head>
<body>
    <h1>404</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500</title>
</head>
<body>
    <h1>500</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误</title>
</head>
<body>
    <h1>错误</h1>
    <div>
        <div th:utext="'&lt;!--'" th:remove="tag"></div>
        <div th:utext="'Failed Request URL : ' + ${url}" th:remove="tag"></div>
        <div th:utext="'Exception message : ' + ${exception.message}" th:remove="tag"></div>
        <ul th:remove="tag">
            <li th:each="st : ${exception.stackTrace}" th:remove="tag"><span th:utext="${st}" th:remove="tag"></span></li>
        </ul>
        <div th:utext="'--&gt;'" th:remove="tag"></div>
    </div>
</body>
</html>
  1. 创建一个测试error的类web.IndexController.class测试自己的错误能否实现
package com.sli.web;

import com.sli.Exception.NotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
 * @author 1_f_
 * @create 2021-10-06 18:48
 */
@Controller
public class IndexController {

    @GetMapping("/")
    public String index(){
        //int i = 9/0;
        String blog = null;
        if (blog==null){
            throw new NotFoundException("博客不存在");
        }
        return "index";
    }
}
  1. 创建Exception.NotFoundException.class
package com.sli.Exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
 * @author 1_f_
 * @create 2021-10-06 19:31
 */
@ResponseStatus(HttpStatus.NOT_FOUND)//NOT_FOUND就会将NotFoundException返回成资源找不到的状态(404)
public class NotFoundException extends RuntimeException{
    public NotFoundException() {
    }
    public NotFoundException(String message) {
        super(message);
    }
    public NotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}
  1. 创建拦截器handler.ControllerExceptionHandler.class
package com.sli.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 1_f_
 * @create 2021-10-06 18:56
 */
//拦截异常并返回到自己的页面

//会扫描并拦截带controller注解的注解
@ControllerAdvice
public class ControllerExceptionHandler {

    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);
        //返回到自定义的error页面上
        mv.setViewName("error/error");
        return mv;
    }
}
  1. 启动主类进行测试发现能正常跳转到404页面

posted @ 2021-10-06 19:50  1_f  阅读(39)  评论(0)    收藏  举报