<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring Boot `@ExceptionHandler` > 原文: [http://zetcode.com/springboot/exceptionhandler/](http://zetcode.com/springboot/exceptionhandler/) Spring Boot `@ExceptionHandler`教程展示了如何使用 Spring `@ExceptionHandler`處理異常。 Spring 是流行的 Java 應用框架,而 Spring Boot 是 Spring 的演進,可以幫助輕松地創建獨立的,生產級的基于 Spring 的應用。 `@ExceptionHandler`是用于在特定處理器類或處理器方法中處理異常的注解。 在 Servlet 環境中,我們可以將`@ExceptionHandler`注解與`@ResponseStatus`結合起來以定義 HTTP 響應的響應狀態。 ## Spring Boot `@ExceptionHandler`示例 在以下應用中,我們演示`@ExceptionHandler`的用法。 主頁中的 HTML 鏈接調用控制器的方法,該方法將返回數據或引發異常。 ```java pom.xml src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── Application.java │ │ ├── controller │ │ │ └── MyController.java │ │ ├── exception │ │ │ └── MyDataException.java │ │ └── service │ │ ├── IDataService.java │ │ └── MyDataService.java │ └── resources │ ├── static │ │ ├── index.html │ │ └── showError.html │ └── templates │ └── showData.ftl └── test └── java ``` 這是 Spring 應用的項目結構。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>springbootexceptionhandlerex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 這是 Maven `pom.xml`文件。 `spring-boot-starter-freemarker`是 Freemarker 模板引擎的依賴項; `spring-boot-maven-plugin`將 Spring 應用打包到可執行的 JAR 或 WAR 歸檔文件中。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import com.zetcode.exception.MyDataException; import com.zetcode.service.IDataService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.Map; @Controller public class MyController { @Autowired private IDataService dataService; @RequestMapping(value = "/getData") public ModelAndView getData() { var data = dataService.findAll(); Map<String, Object> params = new HashMap<>(); params.put("values", data); return new ModelAndView("showData", params); } @ExceptionHandler(MyDataException.class) public String handleError(MyDataException e) { return "redirect:/showError.html"; } } ``` `MyController`的`getData()`方法調用服務方法,并將檢索到的數據存儲到列表中。 數據被發送到`showData`視圖。 如果是`MyDataException`,則控制器將重定向到錯誤頁面。 ```java @ExceptionHandler(MyDataException.class) public String handleError(MyDataException e) { return "redirect:/showError.html"; } ``` `handleError()`用`@ExceptionHandler`裝飾。 `MyDataException`的處理器已激活。 在方法的主體中,我們重定向到`showError.html`頁面。 `com/zetcode/exception/MyDataException.java` ```java package com.zetcode.exception; public class MyDataException extends RuntimeException { public MyDataException(String message) { super(message); } } ``` 我們定義一個自定義`MyDataException`。 `com/zetcode/service/IDataService.java` ```java package com.zetcode.service; import java.util.List; public interface IDataService { List<String> findAll(); } ``` `IDataService`包含契約方法。 `com/zetcode/service/MyDataService.java` ```java package com.zetcode.service; import com.zetcode.exception.MyDataException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.springframework.stereotype.Service; @Service public class MyDataService implements IDataService { @Override public List<String> findAll() { var r = new Random(); if (r.nextBoolean()) { throw new MyDataException("Failed to retrieve data"); } var data = new ArrayList<String>(); data.add("yellow moon"); data.add("brisk pace"); data.add("empty bottle"); data.add("beautiful weather"); return data; } } ``` `MyDataService`實現`IDataService`的`findAll()`方法。 該方法返回數據或拋出`MyDataException`。 ```java var r = new Random(); if (r.nextBoolean()) { throw new MyDataException("Failed to retrieve data"); } ``` `findAll()`方法隨機拋出`MyDataException`。 然后在控制器中處理異常。 ```java var data = new ArrayList<>(); data.add("yellow moon"); data.add("brisk pace"); data.add("empty bottle"); data.add("beautiful weather"); return data; ``` 如果沒有例外,我們將返回一個字符串列表。 `resources/static/index.html` ```java <!DOCTYPE html> <html> <head> <title>Home page</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <a href="/getData">Get data</a> </body> </html> ``` 這是主頁。 它包含一個鏈接,該鏈接調用我們的控制器方法以獲取一些數據。 `resources/static/showError.html` ```java <!DOCTYPE html> <html> <head> <title>Error</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p>Failed to retrieve data</p> </body> </html> ``` 這是一個錯誤頁面。 拋出`MyDataException`時顯示。 `resources/templates/showData.ftl` ```java <!DOCTYPE html> <html> <head> <title>Data</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>Data</h2> <ul> <#list values as val> <li>${val}</td> </#list> </ul> </body> </html> ``` `showData.ftl`是一個 Freemarker 模板文件,它在 HTML 列表中顯示所有檢索到的數據。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`是引導 Spring Boot 應用的入口點。 在本教程中,我們展示了如何使用`@ExceptionHandler`在 Spring 應用中處理異常。 您可能也對相關教程感興趣: [Spring Boot Flash 屬性教程](/springboot/flashattribute/), [Spring Boot `@ResponseStatus`教程](/springboot/responsestatus/), [Spring Boot `@PathVariable`教程](/springboot/pathvariable/), [Spring Boot `@RequestParam`教程](/springboot/requestparam/), [Java 教程](/lang/java/),或顯示[所有 Spring Boot 教程](/all/#springboot)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看