天河做网站,长沙电商网站制作,网站后台培训学校,mysql网站开发创建Spring Boot项目#xff1a;使用Spring Initializr创建一个新的Spring Boot项目。依赖配置#xff1a;在pom.xml 文件中(方便起见使用的是thymeleaf模板引擎)#xff1a;
dependenciesdependencygroupIdorg.springframework.boot/groupId使用Spring Initializr创建一个新的Spring Boot项目。依赖配置在pom.xml 文件中(方便起见使用的是thymeleaf模板引擎)
dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency
/dependenciesHTML目录结构在src/main/resources/templates 目录下创建HTML视图。这里提供两个示例视图error-page.html 和 result-page.html
error-page.html
!DOCTYPE html
html xmlns:thhttp://www.thymeleaf.org
headtitle错误页面/title
/head
body
h1错误/h1
p th:text${message}/p
/body
/htmlresult-page.html
!DOCTYPE html
html xmlns:thhttp://www.thymeleaf.org
headtitle结果页面/title
/head
body
h1结果/h1
p th:text结果是 ${result}/p
/body
/html定义自定义异常类创建一个自定义异常类例如 MyCustomException
public class MyCustomException extends Exception {public MyCustomException(String message) {super(message);}
}异常处理器类创建一个异常处理器类 MyCustomExceptionHandler并配置多个ExceptionHandler 方法来处理不同类型的异常
import com.lfsun.demolfsunstudythymeleafcustomexception.exception.MyCustomException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;ControllerAdvice
public class MyCustomExceptionHandler {ExceptionHandler(MyCustomException.class)public ModelAndView handleCustomException(MyCustomException ex) {ModelAndView modelAndView new ModelAndView();modelAndView.addObject(message, 自定义异常发生了 ex.getMessage());modelAndView.setViewName(error-page);return modelAndView;}ExceptionHandler(Exception.class)public ModelAndView handleAllOtherExceptions(Exception ex) {ModelAndView modelAndView new ModelAndView();modelAndView.addObject(message, 发生了其他异常 ex.getMessage());modelAndView.setViewName(error-page);return modelAndView;}
}控制器类创建一个控制器类例如 DemoController并在其中抛出自定义异常
import com.lfsun.demolfsunstudythymeleafcustomexception.exception.MyCustomException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;Controller
public class DemoController {GetMapping(/divide)public String divide(RequestParam int dividend, RequestParam int divisor, Model model) throws MyCustomException {if (divisor 0) {throw new MyCustomException(不允许除以零。);}int result dividend / divisor;model.addAttribute(result, result);return result-page;}
}运行项目运行Spring Boot应用程序。访问应用程序在浏览器中访问 http://localhost:8080/divide?dividend10divisor2 这个URL将会执行 DemoController 中的 divide 方法并显示结果5。尝试访问 http://localhost:8080/divide?dividend10divisor0 来看到自定义异常处理器的效果。