ps: Recommend my general background management project crowd-admin as well as newbee-mall Enhanced version , If you like, give me star Just fine

Source code analysis

stay springboot There is an exception handler interface by default in ErrorContorller, This interface provides getErrorPath() Method , The BasicErrorController The implementation class implements getErrorPath() Method , as follows :


/*
* AbstractErrorController yes ErrorContoller Implementation class of
*/
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController { private final ErrorProperties errorProperties; ...
@Override
public String getErrorPath() {
return this.errorProperties.getPath();
} @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections
.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
} @RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<>(status);
}
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
....
}

errorProperties Class is defined as follows :

public class ErrorProperties {
/**
* Path of the error controller.
*/
@Value("${error.path:/error}")
private String path = "/error";
...
}

thus it can be seen ,springboot There is a process by default in /error Mapped controllers , Yes error and errorHtml The existence of two methods , It can handle pages from browsers and clients from machines (app application ) Request .

When a user requests something that doesn't exist url when ,dispatcherServlet It's up to ResourceHttpRequestHandler Map the processor to handle the request , And in handlerRequest In the method , Redirect to /error mapping , The code is as follows :

 @Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // For very general mappings (e.g. "/") we need to check 404 first
Resource resource = getResource(request);
if (resource == null) {
logger.debug("Resource not found");
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
return;
}
...
}

getResource(request) Would call this.resolverChain.resolveResource(request, path, getLocations()) Method ,getLocations() Method returns the following :

And then the program goes to getResource(pathToUse, location) The method is as follows :

 @Nullable
protected Resource getResource(String resourcePath, Resource location) throws IOException {
// Create a new one resource object ,url by location + resourcePath, Judge this object ( file ) Whether there is
Resource resource = location.createRelative(resourcePath);
if (resource.isReadable()) {
if (checkResource(resource, location)) {
return resource;
}
else if (logger.isWarnEnabled()) {
Resource[] allowedLocations = getAllowedLocations();
logger.warn("Resource path \"" + resourcePath + "\" was successfully resolved " +
"but resource \"" + resource.getURL() + "\" is neither under the " +
"current location \"" + location.getURL() + "\" nor under any of the " +
"allowed locations " + (allowedLocations != null ? Arrays.asList(allowedLocations) : "[]"));
}
}
return null;
}

stay resource.isReadable() in , The program will in locations Look for path Files under directory , Because there is no , return null.

Eventually, the program will be redirected to /error mapping , If it's a request from a browser , And it will return /template/error/404.html page , So for 404 request , Only need template New under the directory error Catalog , Put in 404 page .

Use caution

  1. stay springboot4.x We can customize ControllerAdvice annotation + ExceptionHandler Annotation to handle exceptions of different error types , But in springboot in 404 Exception and interceptor exception are caused by spring Do it yourself .

springboot Exception handling 404 More articles about

  1. Springboot Exception handling and custom error page

    1. Abnormal source To handle exceptions that occur in the program , First you need to know where the exception comes from ? 1. Front end wrong request path , It makes the program happen 4xx error , The most common is 404,Springboot By default, when this error occurs, the request path ,pc End response page ...

  2. SpringBoot I'll do the exception handling - Use article

    SpringBoot I'll do the exception handling - Use article brief introduction I'll write the repeat function . stay SpringBoot There are global exception handling and return packing in the project , Back to the front is to take succ.code.msg.data Etc . Single ...

  3. To configure springboot During a visit to 404 User defined return results and unified exception handling

    When building the project framework, we use springboot, Want to handle exceptions in a unified way , But found 404 You can't catch your mistakes , What always comes back is springBoot Error result information that comes with it . The following is springBoot Error result information that comes with it : ...

  4. 【 Use part two 】SpringBoot exception handling (9)

    There are many ways to handle exceptions : Custom error page @ExceptionHandler annotation @ControllerAdvice+@ExceptionHandler annotation To configure SimpleMappingExcepti ...

  5. SpringBoot exception handling

    Best practices for exception handling According to my work experience , I mainly follow the following points : Try not to write... In code try...catch.finally Eat the anomaly . Exceptions should be as intuitive as possible , Avoid being misunderstood by others Exceptions are divided into the following categories , Business exceptions , Registration certificate ...

  6. springBoot exception handling

    1.status=404 Whitelabel Error Page Whitelabel Error Page This application has no explicit mapping fo ...

  7. springboot Access request 404 problem

    The novice just came into contact with springboot When , There may be access requests 404 The situation of , There's no problem with the code , But it is 404. doubt : When you're absolutely sure the code is OK , You can see if there is something wrong with your bag ? reason :SpringBoot annotation ...

  8. springboot Engineering additions 404 page

    First, in the /src/main/resources Create folder /public/error Create in folder html page ,jsp Pages can't . <html> <body> <img ...

  9. SpringBoot Study 15:springboot Exception handling 5( By implementing HandlerExceptionResolver class )

    Modify exception handling 4 Global exception handling in controller package com.bjsxt.exception; import org.springframework.context.annotati ...

  10. SpringBoot Study 14:springboot Exception handling 4( Use SimpleMappingExceptionResolver Handling exceptions )

    Modify exception handling methods 3 Global exception handling in Controller that will do package bjsxt.exception; import org.springframework.context.annotation ...

Random recommendation

  1. stay .NET Core Set global exception handling in the program

    Previously, we only needed such code to set up global exception handling : AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledExc ...

  2. paip.python Connect mysql Best practices o4

    paip.python Connect mysql Best practices o4 python Connect mysql It took a lot of time ..., comparison php It's more difficult .. troublesome .. and php, It's easy, Doran .. python The standard library doesn't have mysql library , only ...

  3. Common Converters in WPF/Silverlight

    using System; using System.ComponentModel; using System.Globalization; using System.Windows.Data; na ...

  4. 【 With your hand - Do you have time to tidy up 】Linux With your hand

    1. CentOS6.5 install g++:yum install gcc-c++ Notice if it's written as yum install g++ Will prompt No package g++ available. 2. XShell Open down ...

  5. 【 Code Notes 】Web-JavaScript-JavaScript JSON

    One , design sketch . Two , Code . <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  6. Java Concurrent ——Fork/Join Framework and ForkJoinPool

    In order to prevent unscrupulous web crawlers from grabbing articles , This is to mark , Reprint please indicate the source of the article .LaplaceDemon/ShiJiaqi. http://www.cnblogs.com/shijiaqi1066/p/4631466. ...

  7. Drop down the selection box QCombox

    The style of the drop-down list box is shown in the figure : Font list box style : import sys from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QFontCo ...

  8. Reprint : Delete github There are two ways to open a folder

    http://www.jianshu.com/p/286be61bb9b8 Delete github There are two ways to open a folder ( The solution has joined ignore Unable to delete the folder from the remote warehouse ) If this folder has been added git chase ...

  9. JavaScript Standard object

    1.Date var now = new Date(); now; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST) now.getFullYear(); // 2 ...

  10. C# Parse the array form of json data

    When learning, I come across some problems json Data problems , We also searched a lot of information on the Internet to realize it , Write it down so you can read it . 1. Download the open source class library Newtonsoft.Json( Download address http://json.codeplex.com/, ...