简体   繁体   中英

Checking database connectivity in JSP

How can I check the database connectivity in 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. 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.

Here's an example of a "DAO" class which does all the JDBC stuff on the User table:

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. Here's an example of a 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

<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 . It will by default end up in a container-default HTTP 500 error page. You can if necessary customize this with a JSP in your own look'n'feel as follows

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

Avoid scriplets in jsp, use jstl sql library inside jsp's. 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.

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

How can I check the database connectivity in JSP.

The better design would be to check it at app deploy time and share the connection from applicationContext.

You can also use connection-pooling.

and yes don't write java code in JSP

See Also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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