簡體   English   中英

spring boot中實現自定義錯誤

[英]Implement the custom error in spring boot

我想在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 列旁邊有一條消息。

您可以通過 javascript/jQuery 做到這一點,只需編寫一個小函數,它正在偵聽頁面的 DOM。 因此,在單擊提交時,您可以顯示錯誤消息、顯示模式或重定向到另一個通用錯誤頁面。

如果您希望服務器進行此控件,spring 提供了驚人的 apis 用於驗證,請在 google 上搜索 BindingResult Spring。

其背后的想法非常簡單。 您的控制器將從表單中獲取一個對象,您可以通過在其上使用一些注釋來驗證它。

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

希望能幫助到你

我建議像這個例子一樣開發一個 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;
}

並且您可以將測試條件添加到您的基本控制器,這意味着您希望重定向到錯誤內容的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM