美文网首页Java 杂谈程序员
18,添加错误页面跳转

18,添加错误页面跳转

作者: 滔滔逐浪 | 来源:发表于2019-01-04 11:47 被阅读7次
1,定义404.html,500.html,error.html      

2,定义AppErrorController
package com.yuiyu.project2.controller;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class AppErrorController implements ErrorController {
  @Override
    public String getErrorPath() {
        return "/error";
    }
   @RequestMapping("/error")
    public void handleError(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
 PrintWriter out = response.getWriter();
        if (status != null) {
            Integer statusCode = Integer.valueOf(status.toString());
  if (statusCode == HttpStatus.NOT_FOUND.value()) {
                out.println("<script>top.location.href = '/404.html'</script>");
 } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                out.println("<script>top.location.href = '/500.html'</script>");

            }

  }
        out.println("<script>top.location.href = '/error.html'</script>");
    }
}

3,拦截错误信息

package com.yuiyu.project2;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class HelloApplication  implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage page404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error");
        ErrorPage page500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error");
       registry.addErrorPages(page404, page500);

    }

}


//捕获全局异常的另外一个方法

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice(basePackages = "com.nvli.chapter10")//扫描到该位置
public class GlobalWeceptionHandler {
    @ExceptionHandler(RuntimeException.class)
  @ResponseBody
    public Map<String,Object> errorResult(){
        Map<String,Object> errorResultMap = new HashMap<String,Object>();
        errorResultMap.put("errorcode","500");
           errorResultMap.put("errorMsg","系统错误");
        return errorResultMap;

 }

}

相关文章

网友评论

    本文标题:18,添加错误页面跳转

    本文链接:https://www.haomeiwen.com/subject/hsmwlqtx.html