Spring Boot 实现ErrorController接口处理404、500等错误页面
在项目中我们遇到404找不到的错误、或者500服务器错误都需要配置相应的页面给用户一个友好的提示,而在Spring Boot中我们需要如何设置。
我们需要实现ErrorController接口,重写handleError方法。
package com.ciyou.edu.controller
import org.springframework.boot.autoconfigure.web.ErrorController
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import javax.servlet.http.HttpServletRequest
@Controller
class MainsiteErrorController implements ErrorController {
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request){
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code")
        if(statusCode == 401){
            return "/401"
        }else if(statusCode == 404){
            return "/404"
        }else if(statusCode == 403){
            return "/403"
        }else{
            return "/500"
        }
    }
    @Override
    public String getErrorPath() {
        return "/error"
    }
}通过上述设置就可以实现对应状态码跳转到对应的提示页面了。
 
                     
                    
                 
                    
                 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号