JSP(JavaServer Pages)是一种用于创建动态Web内容的技术,它允许开发者将Java代码嵌入到HTML页面中,从而实现服务器端的动态处理。下面我将为你提供一个简单的JSP购书网站的源代码示例,包括一些基础概念和相关优势。
以下是一个简单的JSP购书网站的部分源代码示例:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>购书网站</title>
</head>
<body>
<h1>欢迎来到购书网站</h1>
<form action="searchBooks.jsp" method="get">
<input type="text" name="keyword" placeholder="搜索书籍">
<input type="submit" value="搜索">
</form>
</body>
</html>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>搜索结果</title>
</head>
<body>
<h1>搜索结果</h1>
<%
String keyword = request.getParameter("keyword");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore", "username", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM books WHERE title LIKE '%" + keyword + "%'");
%>
<ul>
<% while (rs.next()) { %>
<li><%= rs.getString("title") %> - <%= rs.getString("author") %></li>
<% } %>
</ul>
<%
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
</body>
</html>
问题:数据库连接失败或查询无结果。
原因:
解决方法:
希望这些信息对你有所帮助!如果你有其他具体问题或需要进一步的代码示例,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云