[英]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.