检查JSP中的数据库连接



如何在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。默认情况下,它将出现在容器默认的HTTP500错误页面中。如有必要,您可以在自己的外观中使用JSP进行自定义,如下所示

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

另请参阅:

  • 如何避免JSP文件中的Java代码
  • DAO教程-基本代码示例

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

    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中进行数据库连接。

避免在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>

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

更好的设计是在应用程序部署时检查它,并从applicationContext共享连接。

您也可以使用连接池。

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

另请参见

  • 为什么业务逻辑应该移出jsp

使用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框架教程

最新更新