0

如何检查 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();

连接成功后,我想向数据库中插入数据。我还想检查数据是否正确插入。任何人都可以帮我解决这个问题...

4

5 回答 5

3

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>

也可以看看:

于 2011-06-01T13:01:36.527 回答
1

避免在 jsp 中使用 scriplets,在 jsp 中使用 jstl sql 库。示例代码在这里

<c:catch var ="catchException">
The exception will be thrown inside the catch:<br>
<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql//localhost/datasouce" user="admin" password="passowrd"/>
<sql:query var="ids" dataSource="${dataSource}">SELECT * FROM table</sql:query>
</c:catch>
<c:if test = "${catchException!=null}">The exception is : ${catchException}<br><br>There is an exception: ${catchException.message}<br></c:if>
于 2011-06-01T12:14:06.057 回答
1

您的代码是完美的确定数据库连接:

    try {
            conn = java.sql.DriverManager.getConnection(connectionUrl);
            System.out.println("Connection established");
            //--- Do operation on database.
    }
    catch (Exception e) {
            System.out.println(e);
            System.out.println("Connection not established");
    }

尽量避免在jsp中进行此操作,最好在servlet中进行数据库连接。

于 2011-06-01T12:07:51.777 回答
0

使用 try catch 和 if-else 语句检查数据是否正确插入,如果在插入事务过程中出现错误,则使用回滚。

Connection conn = null;
Statement stmt = null;

try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost;databaseName=dbname;user=username;password=password";
conn = DriverManager.getConnection(connectionUrl); 
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
stmt.executeUpdate(sql);
stmt.executeUpdate(sql);
stmt.executeUpdate(sql);

conn.commit();
}
catch(Exception e) {
if(!conn.isClosed()){
conn.rollback();
}
System.out.println(e);
}
finally{
if(!stmt.isClosed()){
stmt.close();
}
if(!conn.isClosed()){
conn.close();
}
}

或尝试使用 JSTL 更轻松 观看JSF 框架教程

于 2013-06-05T20:04:37.730 回答
0

如何检查 JSP 中的数据库连接。

更好的设计是在应用部署时检查它并共享来自 applicationContext 的连接。

您还可以使用连接池。

是的,不要在 JSP 中编写 java 代码

也可以看看

于 2011-06-01T12:12:21.503 回答