gpt4 book ai didi

java - 检查 JSP 中的数据库连接

转载 作者:行者123 更新时间:2023-12-01 17:36:04 25 4
gpt4 key购买 nike

如何在 JSP 中检查数据库连接。如果数据库连接出现任何问题,我想打印一条错误消息。

我使用以下代码:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost;databaseName=dbname;user=username;password=password";
Connection conn = DriverManager.getConnection(connectionUrl);
Statement stmt = conn.createStatement();

连接成功后,我想向数据库中插入数据。我还想检查数据是否正确插入。谁能帮我解决这个问题...

最佳答案

JSP 不适合这样做。您需要创建一个独立的类来执行 JDBC 作业,并让每个方法在 SQL 失败时抛出异常。

下面是一个“DAO”类的示例,它在 User 表上执行所有 JDBC 操作:

public class UserDAO {

public User find(String username, String password) throws SQLException {
// ...
}

public void save(User user) throws SQLException {
// ...
}

public void delete(User user) throws SQLException {
// ...
}

}

然后,创建一个 servlet它使用此类并处理异常。以下是 LoginServlet 的示例:

@WebServlet(urlPatterns={"/login"})
public class LoginServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDAO = new UserDAO();

try {
User user = userDAO.find(username, password);

if (user != null) {
request.getSession().setAttribute("user", user); // Login.
response.sendRedirect("userhome");
} else {
request.setAttribute("message", "Unknown login, try again"); // Set error message.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Redisplay form with error.
}
} catch (SQLException e) {
throw new ServletException("Fatal database failure", e); // <-- Here
}
}

}

让JSP提交到这个servlet

<form action="login" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
${message}
</form>

您会看到,当 DAO 类抛出 SQLException 时,servlet 将其重新抛出为 ServletException。默认情况下,它将出现在容器默认的 HTTP 500 错误页面中。如果需要,您可以使用 JSP 按照您自己的外观进行自定义,如下所示

<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>

另请参阅:

关于java - 检查 JSP 中的数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6200833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com