[英]Checking database connectivity in 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 是錯誤的地方。 您需要創建一個獨立的 class 來執行 JDBC 作業,並讓每個方法在 SQL 內容失敗時拋出異常。
這是“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 {
// ...
}
}
然后,創建一個使用此 class 並處理異常的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 class 拋出SQLException
時,servlet 將其重新拋出為ServletException
。 默認情況下,它將在容器默認 HTTP 500 錯誤頁面中結束。 如有必要,您可以使用 JSP 在您自己的外觀中自定義它,如下所示
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
您的代碼是完美的確定數據庫連接:
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 中的腳本,在 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>
使用 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 框架教程
如何檢查 JSP 中的數據庫連接。
更好的設計是在應用部署時檢查它並共享來自 applicationContext 的連接。
您還可以使用連接池。
是的,不要在 JSP 中寫 java 代碼
也可以看看
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.