java - Spring boot如何实现错误页面

标签 java spring hibernate spring-boot spring-mvc

我正在尝试制作一个 Spring 应用程序,如果客户尝试购买没有库存的产品,该应用程序会出现错误页面。 我收到一条错误消息:HTTP Status 500 - 请求处理失败;每当我尝试测试它时,嵌套异常都是 java.lang.NullPointerException 。我尝试了很多方法,我觉得我已经很接近了。

请参阅下面的 Controller ,错误类只有 getter 和 setter 等

任何帮助将不胜感激!!!

package com.sales.controllers;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.taglibs.standard.lang.jstl.LessThanOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sales.exceptions.ErrorController;
import com.sales.models.Customer;
import com.sales.models.Order;
import com.sales.models.Product;
import com.sales.services.CustomerService;
import com.sales.services.OrderService;
import com.sales.services.ProductService;

@Controller                             //implementing the error class here
public class OrderController implements org.springframework.boot.autoconfigure.web.ErrorController {

    @Autowired
    ProductService ps;

    @Autowired
    CustomerService cs;

    @Autowired
    OrderService os;

    private Product prod;
    private Customer cust;

    ErrorController ec;



    @RequestMapping(value = "/showOrders.html")
    public String listOrders(Model model) {

        ArrayList<Order> orders = os.findAll();
        model.addAttribute("allOrders", orders);

        ArrayList<Customer> cust = cs.findAll();
        model.addAttribute("ordrs", cust);
        return "allOrders";
    }

    @RequestMapping(value = "/newOrder.html", method = RequestMethod.GET)
    public String addPerson(Model model) {
        ArrayList<Customer> customer = cs.findAll();
        ArrayList<Product> product = ps.findAll();

        Map<Long, String> customers = new LinkedHashMap<Long, String>();
        for (Customer c : customer) {
            customers.put(c.getcId(), c.getcName());

            model.addAttribute("customers", customers);

            Map<Long, String> products = new LinkedHashMap<Long, String>();
            for (Product p : product) {
                products.put(p.getpId(), p.getpDesc());

                model.addAttribute("products", products);
            }

        }
        Order o = new Order();

        model.addAttribute("orderList", o);

        return "addOrder";

    }

    @RequestMapping(value = "/newOrder.html", method = RequestMethod.POST)
    public String addOrderPost(@Valid @ModelAttribute("orderList") Order o, BindingResult result) {

        boolean qty = false;

        System.out.println("In order add");

        if (result.hasErrors()) {
            return "addOrder";
        }

        prod = ps.findOne(o.getProd().getpId());
        cust = cs.findOne(o.getCust().getcId());

        o.setProd(prod);
        prod.setQtyInStock(prod.getQtyInStock() - (o.getQty()));

        //if this happens the user should be redireccted with the following headings and error
        if (prod.getQtyInStock() < (o.getQty())) {
            ec.setHeader("Error creating the following order");
            ec.setError("Quantity to large: " + "Product stock" + prod.getQtyInStock());

            return "redirect:errorPage";
        }

        os.save(o);

        return "redirect:showOrders.html";

    }

    // Object that holds info related to the errors

        private static final String PATH = "/error";

        // adds ec object to the model and user is moved to the errorPage and error is
        // displayed
        @RequestMapping(value = PATH)
        public String errorPage(Model model) {

            System.out.println(ec.getHeader());
            System.out.println(ec.getError());

            model.addAttribute("exception", ec);

            return "errorPage";
        }
        @Override
        public String getErrorPath() {
            return PATH;
        }

}

错误页面(JSP)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <h1>${exception.header}</h1>
  <h2>${exception.error}</h2>
</body>
</html>


最佳答案

您需要处理您的异常类型的异常处理程序或处理任何类型异常的异常处理程序。

我个人更喜欢全局应用程序异常处理程序。它们是在 @ControllerAdvice 注释的帮助下创建的:

@ControllerAdvice
public class ResponseExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAnyException(HttpServletRequest request, Exception e) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("your-error-page");

        return modelAndView;
    }
}

这个异常处理程序将处理应用程序中任何类型的异常,因为它处理 -> @ExceptionHandler(Exception.class) -> Exception.class。

如果您需要处理特定异常并提供不同的页面,则需要将特定异常类放入@ControllerAdvice。

示例:

    @ExceptionHandler(CustomException.class)
    public ModelAndView handleAnyException(HttpServletRequest request, CustomException e) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("your-custom-page");

        return modelAndView;
    }

关于异常处理的好文章:https://www.baeldung.com/exception-handling-for-rest-with-spring

关于java - Spring boot如何实现错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61477776/

相关文章:

java - 在 mongodb 中保存带日期的时区

java - 更改序列 H2DB 的数据类型

java - Statement.executeUpdate() 返回 -1 是什么意思?

java - 我可以将多个表单输入绑定(bind)到一个 bean 的一个属性吗?

java - 如何使用外键在 Spring Data/JPA 中执行查询?

java - 在内存数据库中从 MySQL 切换到 Hypersonic 时出现 SQL 语法异常

java - 在 Web 应用程序中在何处以及如何存储和检索图像?

java - 将两个长变量相除然后相减得到零

java - Spring - 使用模拟进行单元测试 - 如何在服务单元测试中模拟自定义收集器

java - 如何在spring中从rest url获取包含点(.)的参数