[英]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.