jsp新书入库,完成图书的添加操作。添加成功返回图书列表页面
时间: 2023-06-16 07:07:59 浏览: 202
好的,你需要编写一个后端接口来处理这个功能。首先,你需要定义一个 Book 类,用于存储图书信息。
```java
public class Book {
private String id; // 图书编号
private String name; // 图书名称
private String author; // 作者
private String publisher; // 出版社
private Date publishDate; // 出版日期
// 省略 getter 和 setter 方法
}
```
然后,你需要编写一个 BookDao 类,用于操作数据库。这里使用 JDBC 技术来连接数据库,并进行增删改查操作。
```java
public class BookDao {
private Connection conn;
public BookDao() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public void addBook(Book book) {
try {
PreparedStatement ps = conn.prepareStatement("insert into book(id, name, author, publisher, publish_date) values (?, ?, ?, ?, ?)");
ps.setString(1, book.getId());
ps.setString(2, book.getName());
ps.setString(3, book.getAuthor());
ps.setString(4, book.getPublisher());
ps.setDate(5, new java.sql.Date(book.getPublishDate().getTime()));
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 省略其他方法
}
```
接着,你需要编写一个 BookController 类,处理图书添加请求。
```java
public class BookController {
private BookDao bookDao;
public BookController() {
bookDao = new BookDao();
}
public void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String author = request.getParameter("author");
String publisher = request.getParameter("publisher");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date publishDate = null;
try {
publishDate = sdf.parse(request.getParameter("publishDate"));
} catch (ParseException e) {
e.printStackTrace();
}
Book book = new Book();
book.setId(id);
book.setName(name);
book.setAuthor(author);
book.setPublisher(publisher);
book.setPublishDate(publishDate);
bookDao.addBook(book);
response.sendRedirect(request.getContextPath() + "/book/list.jsp");
}
}
```
最后,在 web.xml 文件中配置 BookController 的 Servlet 映射。
```xml
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>com.example.BookController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/book/*</url-pattern>
</servlet-mapping>
```
现在,你可以在前端页面中调用 /book/add 接口来添加图书,并跳转到列表页面。
```html
<form action="${pageContext.request.contextPath}/book/add" method="post">
<label for="id">编号:</label>
<input type="text" id="id" name="id">
<br>
<label for="name">名称:</label>
<input type="text" id="name" name="name">
<br>
<label for="author">作者:</label>
<input type="text" id="author" name="author">
<br>
<label for="publisher">出版社:</label>
<input type="text" id="publisher" name="publisher">
<br>
<label for="publishDate">出版日期:</label>
<input type="date" id="publishDate" name="publishDate">
<br>
<input type="submit" value="添加">
</form>
```
阅读全文