【问题标题】:Implement the custom error in spring boot在spring boot中实现自定义错误
【发布时间】:2019-04-07 02:58:26
【问题描述】:

我想在spring boot中实现自定义错误页面。在应用程序中,id 是主键,所以当没有给出 id 时,它会将请求传输到页面,但我希望应用程序在索引页面上显示带有错误消息的索引页面。实体类是

@Entity
public class Employee  {
    @Id
    //@GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    //@Id
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }


    private String name;
    private String phone;
}

索引页是

<!DOCTYPE html>
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index page</title>
</head>
<body>
<form action="#" th:action="@{/result}" th:object="${employee}" method="post">
    <p>Id: <input type="text" th:field="*{id}" /></p>
    <p>name: <input type="text" th:field="*{name}" /></p>
    <p>phone: <input type="text" th:field="*{phone}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>


</body>
</html>

我想在索引页面上显示错误,例如 id 字段更改颜色或在 id 列旁边有一条消息。

【问题讨论】:

标签: java spring spring-mvc spring-boot


【解决方案1】:

我建议像这个例子一样开发一个 customError 控制器: 并影响你的错误html页面(你可以用不同的方式)

@Controller
public class CustomErrorController implements  ErrorController{

private static final String PATH = "/error";
private static final org.slf4j.Logger log = 
LoggerFactory.getLogger(CustomErrorController.class);
 String script_error_page = "<html lang='en' app='HubMonitor'><head><meta 
   charset='UTF-8'><meta name='viewport' content='width=device-width, initial- 
  scale=1'><title>Hub Monitor</title><head>......your html code ....</head></html>";

@RequestMapping("/error")
@ResponseBody
public String handleError(HttpServletRequest request) {

    return script_error_page;
}

你可以在你的基本控制器中添加测试条件,这意味着当你想要被重定向到错误内容时。

【讨论】:

    【解决方案2】:

    您可以通过 javascript/jQuery 来完成此操作,只需编写一个小函数来监听页面的 DOM。 因此,单击提交时,您可以显示错误消息、显示模式或重定向到另一个通用错误页面。

    如果你想让服务器做这个控制,spring 提供了很棒的 api 用于验证,在 google 上搜索 BindingResult Spring。

    它背后的想法很简单。您的控制器将从表单中获取一个对象,您可以通过在其上使用一些注释来验证它。

    我找到了这个例子:https://www.journaldev.com/2668/spring-validation-example-mvc-validator

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 2019-09-27
      • 2020-11-04
      • 1970-01-01
      • 2018-02-11
      • 2014-12-01
      • 2016-03-31
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多