JSP和MYSQL:如何中继SQL异常

时间:2013-05-28 15:33:52

标签: mysql jsp exception-handling

我正在尝试创建一个允许用户输入unqiue ID的登录屏幕。如何将信息中继给用户所选的ID不唯一。到目前为止,我所能做的只是触发异常。

Registration.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Enter Your details here</title>
</head>
<body>
<h3>Enter User ID</h3>
<br>
<form action = "RegistrationServlet" method = "post">
Enter User ID : <input type = "text"  name ="newUserId"/>
<br>Enter your Password : <input type = "password" name ="newUserPassword"/>
<br>Enter your First Name :<input type = "text" name = "newUserFirstName"/>
<br>Enter your Last Name : <input type = "text" name ="newUserLastName"/>
<br><input type = "submit"/>
<br>
<%=session.getAttribute("notUniqueUserID")%>
</form>
</body>
</html>

RegististrationServlet

catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            boolean notUniqueUserID = true;
            request.getSession(notUniqueUserID);
            response.sendRedirect("registration.jsp");
        }

1 个答案:

答案 0 :(得分:0)

这不是最好的解决方案,因为它会重新加载表单,用户需要再次输入所有数据,我建议你使用AJAX进行这种验证。 无论如何,这里是一段代码,用于为请求设置一个属性并将其放入jsp。

的Servlet

}catch (SQLException e) {
            e.printStackTrace();
            boolean notUniqueUserID = true;
            request.setAttribute("notUniqueUserID", "Not Unique User ID");
            request.getRequestDispatcher("registration.jsp").forward(request, response);
        }

JSP:

<%=request.getAttribute("notUniqueUserID")%>