如果在 jsp 中删除记录失败,则显示错误消息

Show error msg if record is failed to be deleted in jsp

我正在开发基于 Web 的应用程序,如果用户认为不需要维护,我需要删除父项。 如果父条目在子条目 table 中没有任何记录,则条目将被删除,但如果它在子条目 table 中有记录,那么我想显示错误消息,其中存在条目 table .

我正在使用 jsp 和 servlet 遵循 MVC 架构。

注意以下几点,如果您的表定义明确,子记录必须引用父记录(阅读有关 FOREIGN KEY 的信息)。然后,如果您尝试删除父记录,您有多种选择:

1- 您可以允许默认模式:如果不先删除子项就不能删除父项(我认为这就是您从描述中想要的)。

2-您可以"say"到mysql在删除父记录的同时删除所有子记录。

有关此的更多信息,请阅读此 post:Foreign key constraints: When to use ON UPDATE and ON DELETE

假设你想遵循第一个选项,当你想删除父键时,可能会发生两件事。

1- 没有子记录,因此一切如你所愿。

2- 您有引用要删除的父记录的子记录。在这种情况下,mysql 不会删除父记录,并且 return 您会收到代码 1217 的错误(无法删除或更新父行:外键约束失败)。然后你可以检测到错误。做你假装用它做的事,在本例中是向客户端显示错误消息。为了显示消息,这里是我 post 在写这个答案之前评论的副本:

Once detected, there are two options, to send the error to the jsp page. You can send it using the user session, or, when you are redirecting to the jsp page, you can send an attribute in the url like www.my-app./jsppage?error=1. Then the jsp page gets the attribute and display the proper error message.