简体   繁体   English

检查 JSP 中的数据库连接

[英]Checking database connectivity in JSP

How can I check the database connectivity in JSP.如何检查 JSP 中的数据库连接。 I want to print an error message if there is any problem occurs with the database connectivity.如果数据库连接出现任何问题,我想打印一条错误消息。

I m using the following code:我正在使用以下代码:

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();

After successfull connection, I want to insert data to the database.连接成功后,我想向数据库中插入数据。 I also want to check the whether the data is inserted properly.我还想检查数据是否正确插入。 Can anyoone help me on this...任何人都可以帮我解决这个问题...

The JSP is the wrong place for this. JSP 是错误的地方。 You need to create a standalone class which does the JDBC job and let each of the methods throw an exception whenever the SQL stuff fails.您需要创建一个独立的 class 来执行 JDBC 作业,并让每个方法在 SQL 内容失败时抛出异常。

Here's an example of a "DAO" class which does all the JDBC stuff on the User table:这是“DAO”class 的示例,它执行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 {
        // ...
    }

}

Then, create a servlet which uses this class and handles the exception.然后,创建一个使用此 class 并处理异常的servlet Here's an example of a LoginServlet :这是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
        }
    }

}

Let JSP submit to this servlet让 JSP 提交给这个 servlet

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

You see, when the DAO class throws an SQLException , the servlet rethrows it as ServletException .您会看到,当 DAO class 抛出SQLException时,servlet 将其重新抛出为ServletException It will by default end up in a container-default HTTP 500 error page.默认情况下,它将在容器默认 HTTP 500 错误页面中结束。 You can if necessary customize this with a JSP in your own look'n'feel as follows如有必要,您可以使用 JSP 在您自己的外观中自定义它,如下所示

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

See also:也可以看看:

Your code is perfect do determine database connection:您的代码是完美的确定数据库连接:

    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");
    }

Try to avoid this operation in jsp better to do database connection in servlet.尽量避免在 jsp 中进行此操作,最好在 servlet 中进行数据库连接。

Avoid scriplets in jsp, use jstl sql library inside jsp's.避免 jsp 中的脚本,在 jsp 中使用 jstl sql 库。 Sample code goes here示例代码在这里

<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>

use try catch and if-else statement to check whether the data insert properly and use rollback if there is error during the insert transaction.使用 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();
}
}

or try to use JSTL to make it easier Watch JSF Framework Tutorials或者尝试使用 JSTL 更容易观看JSF 框架教程

How can I check the database connectivity in JSP.如何检查 JSP 中的数据库连接。

The better design would be to check it at app deploy time and share the connection from applicationContext.更好的设计是在应用部署时检查它并共享来自 applicationContext 的连接。

You can also use connection-pooling.您还可以使用连接池。

and yes don't write java code in JSP是的,不要在 JSP 中写 java 代码

See Also也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM