JSP(Java Server Pages)是一种基于Java技术的动态网页技术,它允许在HTML或XML等静态页面中嵌入Java代码,从而实现动态内容的生成和处理。下面我将为你提供一个简单的JSP网页图书馆管理系统的源代码示例,并解释其基础概念和相关优势。
以下是一个简单的JSP网页图书馆管理系统的部分源代码示例:
import java.sql.*;
public class DBConnection {
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/library";
String user = "root";
String password = "password";
return DriverManager.getConnection(url, user, password);
}
}
public class Book {
private int id;
private String title;
private String author;
private int quantity;
// Getters and Setters
}
<%@ page import="java.sql.*" %>
<%@ page import="com.example.DBConnection" %>
<%@ page import="com.example.Book" %>
<html>
<head>
<title>Add Book</title>
</head>
<body>
<h2>Add New Book</h2>
<form action="addBook.jsp" method="post">
Title: <input type="text" name="title"><br>
Author: <input type="text" name="author"><br>
Quantity: <input type="text" name="quantity"><br>
<input type="submit" value="Add Book">
</form>
<%
if ("POST".equalsIgnoreCase(request.getMethod())) {
String title = request.getParameter("title");
String author = request.getParameter("author");
int quantity = Integer.parseInt(request.getParameter("quantity"));
Book book = new Book();
book.setTitle(title);
book.setAuthor(author);
book.setQuantity(quantity);
try (Connection conn = DBConnection.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO books(title, author, quantity) VALUES (?, ?, ?)")) {
ps.setString(1, book.getTitle());
ps.setString(2, book.getAuthor());
ps.setInt(3, book.getQuantity());
ps.executeUpdate();
out.println("<h3>Book added successfully!</h3>");
} catch (SQLException e) {
out.println("<h3>Error adding book: " + e.getMessage() + "</h3>");
}
}
%>
</body>
</html>
PreparedStatement
代替Statement
,避免SQL注入。希望这些信息对你有所帮助。如果你有更多具体问题或需要进一步的代码示例,请随时提问!
领取专属 10元无门槛券
手把手带您无忧上云