【问题标题】:Checking database connectivity in JSP在 JSP 中检查数据库连接
【发布时间】:2011-09-06 05:57:36
【问题描述】:

如何检查 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 做数据库连接管理,而是从较低的层次做,JSP 应该是主要的呈现。
  • 嗨 Waldheinz 我是 JSP 新手。所以我不知道编码标准。我会努力学习 servlet

标签: java jsp jdbc database-connectivity


【解决方案1】:

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.sql.SQLException 配置错误页面。您可以在哪里自定义 SQL 异常。
【解决方案2】:

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

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

【讨论】:

  • @Dijo:你在用tomcat吗?如果是,则查看日志文件夹中的日志文件。
  • 好的。我会检查日志文件,
  • @Dijo:如果连接成功,您将看到Connection established;如果连接不成功,您将看到Connection not established,然后是异常堆栈跟踪。
  • jsp文件第11行出现错误:/index_en.jsp语法错误,插入“Finally”完成TryStatement
  • @Dijo:给我看看你的代码。我不能假设你的 jsp 页面的第 11 行是什么。
【解决方案3】:

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

【讨论】:

  • 其实也应该避免使用 JSTL SQL(和 XML)标签库。
  • @BaluC 任何具体原因。无论如何,我只是在讲述在 jsp 中测试数据库连接的方法。但是,如果有这样的要求,这是正确的唯一方法。否则使用自定义标签,这也类似于 JSTL 标签对吗?请纠正我!
【解决方案4】:

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

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

您也可以使用连接池。

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

另见

【讨论】:

    【解决方案5】:

    使用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 Framework Tutorials

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 2021-08-17
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2015-07-02
      • 2013-06-29
      • 1970-01-01
      相关资源
      最近更新 更多