一、SpringBoot異常處理
SpringBoot 中對于異常處理提供了五種處理方式。
1.自定義錯誤頁面:
SpringBoot默認的處理異常的機制: SpringBoot默認的已經(jīng)提供了一套處理異常的機制。 一旦程序中出現(xiàn)了異常 SpringBoot 會向/error 的 url 發(fā)送請求。在 SpringBoot 中提供了一個 名為 BasicErrorController 來處理/error 請求,然后跳轉(zhuǎn)到默認顯示異常的頁面來展示異常信息。
如 果 我 們 需 要 將 所 有 的 異 常 同 一 跳 轉(zhuǎn) 到 自 定 義 的 錯 誤 頁 面 , 需 要 再 src/main/resources/templates 目錄下創(chuàng)建 error.html 頁面;頁面名稱必須叫 error。

2.通過@ExceptionHandler處理異常:
用來統(tǒng)一的處理方法拋出的異常;操作示例。
- 修改Controller
@Controller
public class ErrorController {
@RequestMapping("show")
public String show() {
String str = null;
str.length();
// int a=3/0;
return "ok";
}
@ExceptionHandler(value = {java.lang.ArithmeticException.class})
public ModelAndView arithmetic(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("error",e.toString());
mv.setViewName("error");
return mv;
}
}
- 創(chuàng)建頁面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>錯誤頁面</title>
</head>
<body>
<h3 >操作失?。。?!<span th:text="${error}"></span></h3>
</body>
</html>

3.通過@ControllerAdvice 與@ExceptionHandler=處理異常:
@ControllerAdvice是一個增強的Controller用于處理全局異常。
- 創(chuàng)建全局異常處理類:
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(value = {java.lang.NullPointerException.class})
public ModelAndView arithmetic(java.lang.Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("error",e.toString());
mv.setViewName("error2");
return mv;
}
}
- 創(chuàng)建Controller:
@Controller
public class ErrorController {
@RequestMapping("show")
public String show() {
String str = null;
str.length();
// int a=3/0;
return "ok";
}
}
- 創(chuàng)建頁面:
<body>
<h3 >操作失?。。?!<span th:text="${error}"></span></h3>
</body>

4.通過SimpleMappingExceptionResolver對象處理異常:
實現(xiàn)全局異常處理。
- 創(chuàng)建全局異常處理類:
/**
* 全局異常
*/
@Configuration
public class GlobalException2 {
@Bean
public SimpleMappingExceptionResolver getSimpleMapping() {
SimpleMappingExceptionResolver ser = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
//參 數(shù) 一 : 異 常 類 型 , 并且是全名參 數(shù) 二:視圖名稱
properties.put("java.lang.NullPointerException", "error3");
properties.put("java.lang.ArithmeticException", "error4");
ser.setExceptionMappings(properties);
return ser;
}
}
5.通過自定義 HandlerExceptionResolver 對象處理異常:
實現(xiàn)自定義全局異常處理。
- 創(chuàng)建全局異常處理類:
@Configuration
public class GlobalException3 implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv = new ModelAndView();
//判斷不同的異常類型
if (e instanceof NullPointerException){
mv.setViewName("error");
}if (e instanceof ArithmeticException){
mv.setViewName("error");
}
mv.addObject("error",e.toString());
return mv;
}
}
- 創(chuàng)建Controller:
@RequestMapping("show2")
public String show2() {
int a=3/0;
return "ok";
}

二、SpringBoot服務端數(shù)據(jù)校驗
1.實現(xiàn)數(shù)據(jù)校驗:
-
創(chuàng)建項目:
示例 創(chuàng)建實體類并添加校驗規(guī)則:
/**
* @NotNull:對 基 本 數(shù) 據(jù) 類 型 的 對 象 類 型 做 非 空 校 驗
* @NotBlank: 對 字 符 串 類 型 做 非 空 校 驗
* @NotEmpty: 對 集 合 類 型 做 非 空 校 驗
*/
@NotNull(message = "{userid.notnull}")
private Integer userid;
@NotBlank(message = "{username.notnull}")
@Length(max = 10,min = 5,message = "用戶名長度為5~10")
private String username;
@NotNull(message = "{userage.notnull}")
private Integer userage;
- 創(chuàng)建Controller并開啟校驗:
@Controller
@RequestMapping("user")
@Validated
public class UserController {
@RequestMapping("addUser")
public String addUser(@ModelAttribute("blur") @Validated Users users, BindingResult result) {
if (result.hasErrors()) {
// List<ObjectError> list = result.getAllErrors();
// for (ObjectError err:list) {
// FieldError fieldError = (FieldError)err;
// String field = fieldError.getField();
// String message = fieldError.getDefaultMessage();
// System.out.println(field+"----"+message);
// }
return "addUser";
}
System.out.println(users);
return "ok";
}
- 創(chuàng)建頁面:
<body>
<form th:action="@{/user/addUser}" method="post">
<p>
用戶名: <input type="text" name="username"/><font color="red" ><span th:errors="${blur.username}"></span></font>
</p>
<p>
年齡: <input type="text" name="userage"/><font color="red" th:errors="${blur.userage}"></font>
</p>
<p>
<input type="submit" value="添加"/>
</p>
</form>
</body>
- 自定義錯誤提示信息:
@NotNull(message = "用戶ID不能為空")
private Integer userid;
@NotBlank(message = "用戶姓名不能為空")
private String username;
@NotBlank(message = "用戶性別不能為空"
private Integer userage;
-
在配置文件中定義提示信息:
命名規(guī)則
userid.notnull=\u7528\u6237ID\u4e0d\u80fd\u4e3a\u7a7a-
username.notnull=\u7528\u6237\u59d3\u540d\u4e0d\u80fd\u4e3a\u7a7a-
userage.notnull=\u7528\u6237\u5e74\u9f84\u4e0d\u80fd\u4e3a\u7a7a-
-
實現(xiàn)效果:
用戶名和年齡都為空
用戶名長度
2.解決頁面跳轉(zhuǎn)異常:
在html中的獲取result中的錯誤提示,獲取的提示的名字和生成的實體類中的名字對應。
在跳轉(zhuǎn)頁面的方法中注入一個對象,要求參數(shù)對象的變量名必須是對象類型名稱首字母 小寫格式。
- 頁面跳轉(zhuǎn)異常:
@Controller
public class ShowPage {
/**
* 跳 轉(zhuǎn) 頁 面 方 法
* 解 決 異 常 的 方 式 : 可 以 在 跳 轉(zhuǎn) 頁 面 的 方 法 中 注 入 一 個 Users
* 對 象由 于 SprignMVC會 將 該 對 象 放 入 到 Model中 傳 遞 ,
* key的 名 稱 會 使 用該 對 象的 駝 峰 命 名 規(guī) 則 來 作 為 key
*/
@RequestMapping("/{page}")
public String show(@PathVariable String page, @ModelAttribute("blur") Users users) {
System.out.println(page);
return page;
}
}
- 修改Key的名稱:
使用@ModelAttribute注解,對注入的錯誤提示對象更改別名。
@ModelAttribute("blur") Users users
3.其他校驗規(guī)則:
@NotNull: 判斷基本數(shù)據(jù)類型的對象類型是否為 null
@NotBlank: 判斷字符串是否為 null 或者是空串(去掉首尾空格)。
@NotEmpty: 判斷集合是否為空。
@Length: 判斷字符的長度(最大或者最小)
@Min: 判斷數(shù)值最小值
@Max: 判斷數(shù)值最大值
@Email: 判斷郵箱是否合法
4.通過全局異常處理來跳轉(zhuǎn)頁面:
- 對參數(shù)指定校驗規(guī)則:
@PostMapping("/findUser")
public String findUser(@NotBlank(message = "用戶名不能為空") String username) {
System.out.println(username);
return "ok";
}
- 在Controller中開啟校驗:
@Controller
@RequestMapping("user")
@Validated
public class UserController {
- 通過全局異常處理:
@Configuration
public class Exceptions implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv = new ModelAndView();
//判斷不同的異常類型
if (e instanceof NullPointerException){
mv.setViewName("error");
}if (e instanceof ArithmeticException){
mv.setViewName("error");
}if (e instanceof ConstraintViolationException){
mv.setViewName("findUser");
}
mv.addObject("error",e.getMessage().split(":")[1]);
return mv;
}
}
三、SpringBoot整合JUnit單元測試
SpringBoot2.x 使用 Junit5 作為測試平臺,
- @RunWith注解的作用:
@RunWith就是一個運行器;
@RunWith(JUnit4.class)就是指用JUnit4來運行;
@RunWith(SpringJUnit4ClassRunner.class),讓測試運行Spring測試環(huán)境;
@RunWith(Suite.class)的話就是一套測試集合;
- @SpringBootTest注解的作用:
使用@SpringBootTest注解可以運行環(huán)境,測試后臺代碼。
- 修改POM文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<!--junit-vintage-engine提 供 了 Junit3與 Junit4的 運行 平 臺 -->
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2.JUnit5:
- 測試代碼:
public class JunitTest {
public static void JunitDemo(){
System.out.println("測試Junit?。?!");
}
}
@SpringBootTest
class SpringbootSjunitApplicationTests {
@Test
void contextLoads() {
JunitTest.JunitDemo();
}
}

四、SpringBoot熱部署
1.通過DevTools工具實現(xiàn)熱部署:
- 修改POM文件,添加DevTools的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
-
配置IDEA設(shè)置自動編譯:
示例 - 設(shè)置IDEA的Registry:
通過快捷鍵打開該設(shè)置項:Ctrl+Shift+Alt+/ 勾選complier.automake.allow.when.app.running;






