【SpringBoot】单元测试进阶实战、自定义异常处理、t部署war项目到tomcat9和启动原理讲解

========================4、Springboot2.0单元测试进阶实战和自定义异常处理 ==============================

 

1、@SpringBootTest单元测试实战
简介:讲解SpringBoot的单元测试
1、引入相关依赖
<!--springboot程序测试依赖,如果是自动创建项目默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>


2、使用
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程
public class SpringBootTests { }

 


2、SpringBoot测试进阶高级篇之MockMvc讲解
简介:讲解MockMvc类的使用和模拟Http请求实战

1、增加类注解 @AutoConfigureMockMvc
@SpringBootTest(classes={XdclassApplication.class})
2、相关API
perform:执行一个RequestBuilder请求
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn:最后返回相应的MvcResult->Response

 

package com.atguigu.springboot;



import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;



/**
 * 功能描述:测试mockmvc类
 *
 * <p> 创建时间:Apr 24, 2018 10:01:12 PM </p>
 * <p> 作者:小D课堂</p>
 */
@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={SpringBoot04WebRestfulcurdApplication.class}) //启动整个springboot工程
@AutoConfigureMockMvc
public class MockMvcTestDemo {


    @Autowired
    private MockMvc mockMvc;
    @Test
    public void apiTest() throws Exception {

        MvcResult mvcResult =  mockMvc.perform( MockMvcRequestBuilders.get("/test/home") ).
                andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
        int status = mvcResult.getResponse().getStatus();
        System.out.println(status);

    }

}
mockmvctest

 

 

3、SpringBoot2.x个性化启动banner设置和debug日志
简介:自定义应用启动的趣味性日志图标和查看调试日志

1、启动获取更多信息 java -jar xxx.jar --debug

2、修改启动的banner信息
1)在类路径下增加一个banner.txt,里面是启动要输出的信息
2)在applicatoin.properties增加banner文件的路径地址
spring.banner.location=banner.txt

3)官网地址 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-banners

 

 

 

 

 

4、SpringBoot2.x配置全局异常实战
讲解:服务端异常讲解和SpringBoot配置全局异常实战

1、默认异常测试 int i = 1/0,不友好

2、异常注解介绍
@ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody

//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)

 

package com.atguigu.springboot.controller.domain;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class CustomeExtHandler {

    private static final Logger LOG = LoggerFactory.getLogger(CustomeExtHandler.class);


    //捕获全局异常,处理所有不可知的异常
    @ExceptionHandler(value = Exception.class)
    //@ResponseBody
    Object handleException(Exception e, HttpServletRequest request) {
        LOG.error("url {}, msg {}", request.getRequestURL(), e.getMessage());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 100);
        map.put("msg", e.getMessage());
        map.put("url", request.getRequestURL());
        return map;
    }
}
exceptionAdvice

 

 


5、SpringBoot2.x配置全局异常返回自定义页面
简介:使用SpringBoot自定义异常和错误页面跳转实战

1、返回自定义异常界面,需要引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

package com.atguigu.springboot.controller.domain;

public class MyException extends RuntimeException {

    public MyException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private String code;
    private String msg;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

}
自定义exception

 


2、resource目录下新建templates,并新建error.html
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;


https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling

package net.xdclass.demo.domain;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;


@RestControllerAdvice
public class CustomExtHandler {

    private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);

    
    //捕获全局异常,处理所有不可知的异常
    @ExceptionHandler(value=Exception.class)
    Object handleException(Exception e,HttpServletRequest request){
        LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 
        Map<String, Object> map = new HashMap<>();
            map.put("code", 100);
            map.put("msg", e.getMessage());
            map.put("url", request.getRequestURL());
            return map;
    }
    
    

    /**
     * 功能描述:处理自定义异常
     * @return
     */
    @ExceptionHandler(value=MyException.class)
    Object handleMyException(MyException e,HttpServletRequest request){
        //进行页面跳转
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("error.html");
//        modelAndView.addObject("msg", e.getMessage());
//        return modelAndView;
        
        //返回json数据,由前端去判断加载什么页面
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        map.put("url", request.getRequestURL());
        return map;
        
    }
     
    
}
ExceHandler
package net.xdclass.demo.domain;

/**
 * 功能描述:自定义异常类
 *
 * <p> 创建时间:Apr 25, 2018 12:06:51 AM </p> 
 * <p> 作者:小D课堂</p>
 */
public class MyException extends RuntimeException {

    public MyException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private String code;
    private String msg;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

}
MyException
package com.atguigu.springboot.controller;

import com.atguigu.springboot.controller.domain.MyException;
import com.atguigu.springboot.controller.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExcptionController {
    @RequestMapping("/test_ext")
    public Object index(){
        int i=1/0;
        return new User(11,"pwd_123","phone123");
    }
    @RequestMapping("/my_ext")
    public Object myexc(){
        throw new MyException("500","my exception");
    }
}
Controller

 

 

========================5、SpringBoot部署war项目到tomcat9和启动原理讲解 2节课==============================

加入小D课堂技术交流答疑群:Q群:699347262

1、SpringBoot启动方式讲解和部署war项目到tomcat9
简介:SpringBoot常见启动方式讲解和部署war项目Tomcat

1、ide启动
2、jar包方式启动
maven插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
如果没有加,则执行jar包 ,报错如下
java -jar spring-boot-demo-0.0.1-SNAPSHOT.jar
no main manifest attribute, in spring-boot-demo-0.0.1-SNAPSHOT.jar
如果有安装maven 用 mvn spring-boot:run
项目结构
example.jar
|
+-META-INF
| +-MANIFEST.MF
+-org
| +-springframework
| +-boot
| +-loader
| +-<spring boot loader classes>
+-BOOT-INF
+-classes
| +-mycompany
| +-project
| +-YourClasses.class
+-lib
+-dependency1.jar
+-dependency2.jar
目录结构讲解
https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#executable-jar-jar-file-structure

3、war包方式启动
1)在pom.xml中将打包形式 jar 修改为war <packaging>war</packaging>

 

构建项目名称 <finalName>xdclass_springboot</finalName>

 

2)tocmat下载 https://tomcat.apache.org/download-90.cgi

3)修改启动类
public class XdclassApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(XdclassApplication.class);
}

public static void main(String[] args) throws Exception {
SpringApplication.run(XdclassApplication.class, args);
}

}

4)打包项目,启动tomcat

4、启动容器介绍和第三方测试数据讲解

使用Jmter测试工具测试性能(压力测试),QPS(每秒查询书),TPS(每秒失误数),RT(响应时间),判断容器的好坏

https://examples.javacodegeeks.com/enterprise-java/spring/tomcat-vs-jetty-vs-undertow-comparison-of-spring-boot-embedded-servlet-containers/

 

package net.xdclass.base_project;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication //一个注解顶下面3个
public class XdclassApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(XdclassApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(XdclassApplication.class, args);
    }

}
main

 

 

 


2、SpringBoot2.x启动原理概述
简介:讲解SpringBoot启动流程概述和基本加载案例

 

 

posted on 2019-03-12 17:17  打酱油的地方  阅读(267)  评论(0编辑  收藏  举报

导航