spring boot 有自定义的404页面,其体验很不友好,如何修改404页面?
1.修改配置文件yml
spring:
mvc:
throw-exception-if-no-handler-found: true ##如果访问404 抛出异常
resources:
add-mappings: false #不给系统资源添加映射
2.添加全局拦截器
import com.communal.common.responses.ServerResponse;
import com.communal.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
/***
* 统一页面异常处理类
* className GlobalExceptionHandler
* date: 2022-01-06 11:40
* author: yang
**/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler extends BaseController {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public ServerResponse noHandlerEvent(NoHandlerFoundException e) {
log.error("未找到资源的异常:", e);
return custom("您访问的资源不存在");
}
}
最终效果如图