The global exception handler in Spring Boot is the method of unifying error exceptions. Equivalent to the exception handler in SPRINGMVC.
Step One: based on the previous Springboot introduction small demo Modify
Step Two: Modify the Hellocontroller class
Modify the Hellocontroller so that access to/hello is bound to produce an exception: some exception
PackageCn.xdf.springboot.web;ImportJava.text.DateFormat;Importjava.util.Date;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;Importorg.springframework.web.bind.annotation.RequestMapping; @Controller Public classHellocontroller {@RequestMapping ("/hello") PublicString Hello (Model m)throwsexception{M.addattribute ("Now", Dateformat.getdatetimeinstance (). Format (NewDate ())); if (true) {//Manufacturing inevitable exception throw new Exception ("Some Exception exception content! "); } return"Hello";//View redirection hello.jsp }}
Step three: Create the global exception handler class Globalexceptionhandler
A new class Globalexceptionhandler is added to catch the exception exception and its subclasses.
After capturing, put the exception information, send the exception address into the Modelandview , and then jump to errorpage.jsp
Packagecn.xdf.springboot.exception;Importjavax.servlet.http.HttpServletRequest;ImportOrg.springframework.web.bind.annotation.ControllerAdvice;ImportOrg.springframework.web.bind.annotation.ExceptionHandler;ImportOrg.springframework.web.servlet.ModelAndView; @ControllerAdvice//@ControllerAdvice The annotation defines the global exception-handling class Public classGlobalexceptionhandler {@ExceptionHandler (value= Exception.class)//@ExceptionHandler The annotation declares an exception-handling method PublicModelandview Defaulterrorhandler (httpservletrequest req, Exception e)throwsException {modelandview Mav=NewModelandview (); Mav.addobject ("Exception", e);//Exception Content (page display)Mav.addobject ("url", Req.getrequesturl ());//requested URL address (page display)Mav.setviewname ("ErrorPage");//Set the view name returnMav; }}
Step Four: Create errorpage.jsp
errorpage.jsp format it a little better. Show these exception messages
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 " pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><div style=" Width:500px;border : 1px solid lightgray;margin:200px auto;padding:80px "> System has an exception, the reason is: ${exception} <br><br> the address where the exception occurred is: ${url}</div>
</body>
Step Five: Test
Because the hot deployment is configured, you do not have to restart, refresh the page, as follows:
Global exception handler in Spring Boot