Bean+servlet+jsp显示数据库中的一组数据

从数据库中取一组数据放到Bean中:TeamBusiness.java

package business;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import database.DataSource;
import bean.Team;

public class TeamBusiness{
public static  void addTeam(Team team)throws Exception{
Connection cn=null;
PreparedStatement pst=null;
try{
cn=DataSource.getConnection();
pst=cn.prepareStatement("insert into team(name,slogan,leader) values(?,?,?)");
pst.setString(1, team.getName());
pst.setString(2, team.getSlogan());
pst.setString(3, team.getLeader());
pst.executeUpdate();
}catch(Exception e){
throw e;
}finally{
try{
pst.close();
cn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public  static Collection<Team> allTeams() throws Exception {

ArrayList<Team> teams = new ArrayList<Team>();// 创建集合对象

// 从数据库获取数据
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
cn = DataSource.getConnection();
pst = cn.prepareStatement("select * from team");
rs = pst.executeQuery();

while (rs.next()) {
Team team = new Team();// 创建team对象
// 用数据库取得的数据设置team对象的属性
team.setId(rs.getInt("id"));
team.setName(rs.getString("name"));
team.setSlogan(rs.getString("slogan"));
team.setLeader(rs.getString("leader"));

teams.add(team);// 把team对象放到集合teams中
}
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pst.close();
cn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

return teams;
}

}

servlet接收数据并存入request供jsp调用:addTeam1.java

/*
 * 通过mysql来查询表单数据并显示
 */
package servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.Collection;

import bean.Team;
import business.TeamBusiness;

public class viewTeams1 extends HttpServlet{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Collection<Team> teams=TeamBusiness.allTeams();
request.setAttribute("teams", teams);

RequestDispatcher rd = request.getRequestDispatcher("../viewTeams.jsp");
rd.forward(request, response);

} catch (Exception e) {
e.printStackTrace();

RequestDispatcher rd = request.getRequestDispatcher("../viewTeamsFail.jsp");
rd.forward(request, response);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

用jsp取request中的数据并显示:viewTeams.jsp

<?xml version="1.0" encoding="GBK" ?>
<%@ page language="java" contentType="text/html; charset=GBK"
   import="java.util.*,bean.Team;" pageEncoding="GBK"%>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>Insert title here</title>
</head>
<body>
<table border="1" align="center">
<tr><th>组名</th><th>口号</th><th>组长</th></tr>
<%
Collection<Team> teams = (Collection<Team>)request.getAttribute("teams");
Iterator<Team> it = teams.iterator();
while(it.hasNext()) {
Team team = it.next();
%>
<tr>
<td><%=team.getName()%></td>
<td><%=team.getSlogan()%></td>
<td><%=team.getLeader()%></td>
</tr>
<%
}
%>
</table>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是采用JavaBean+Servlet+JSP+DAO的Web架构设计的图书管理系统。 首先,我们需要建立一个图书Bean,包含以下字段: ```java public class Book { private int id; private String name; private String author; private double price; // 构造函数、getters 和 setters 略 } ``` 接下来,我们可以编写一个简单的 DAO 类,使用 JDBC 来实现增删改查操作。例如: ```java public class BookDAO { public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; public static final String DB_URL = "jdbc:mysql://localhost:3306/books"; public static final String USER = "root"; public static final String PASS = "password"; public List<Book> getAllBooks() throws SQLException { List<Book> books = new ArrayList<>(); Connection conn = null; Statement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = "SELECT * FROM book"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Book book = new Book(); book.setId(rs.getInt("id")); book.setName(rs.getString("name")); book.setAuthor(rs.getString("author")); book.setPrice(rs.getDouble("price")); books.add(book); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } return books; } public void addBook(Book book) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "INSERT INTO book (name, author, price) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setString(1, book.getName()); stmt.setString(2, book.getAuthor()); stmt.setDouble(3, book.getPrice()); stmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } public void updateBook(int id, Book book) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "UPDATE book SET name=?, author=?, price=? WHERE id=?"; stmt = conn.prepareStatement(sql); stmt.setString(1, book.getName()); stmt.setString(2, book.getAuthor()); stmt.setDouble(3, book.getPrice()); stmt.setInt(4, id); stmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } public void deleteBook(int id) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "DELETE FROM book WHERE id=?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } } ``` 这个 DAO 类使用 MySQL 数据库存储图书信息,提供了四个方法: - getAllBooks:获取所有图书信息 - addBook:添加一本新书 - updateBook:更新一本图书的信息 - deleteBook:删除一本图书 接下来,我们可以编写一个 Servlet 类,处理 HTTP 请求并调用 DAO 类的方法来实现增删改查操作。例如: ```java public class BookServlet extends HttpServlet { private BookDAO dao = new BookDAO(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Book> books = null; try { books = dao.getAllBooks(); } catch (SQLException e) { e.printStackTrace(); } request.setAttribute("books", books); request.getRequestDispatcher("/book_list.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ("add".equals(action)) { String name = request.getParameter("name"); String author = request.getParameter("author"); double price = Double.parseDouble(request.getParameter("price")); Book book = new Book(); book.setName(name); book.setAuthor(author); book.setPrice(price); try { dao.addBook(book); } catch (SQLException e) { e.printStackTrace(); } } else if ("update".equals(action)) { int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); String author = request.getParameter("author"); double price = Double.parseDouble(request.getParameter("price")); Book book = new Book(); book.setName(name); book.setAuthor(author); book.setPrice(price); try { dao.updateBook(id, book); } catch (SQLException e) { e.printStackTrace(); } } else if ("delete".equals(action)) { int id = Integer.parseInt(request.getParameter("id")); try { dao.deleteBook(id); } catch (SQLException e) { e.printStackTrace(); } } response.sendRedirect(request.getContextPath() + "/book"); } } ``` 这个 Servlet处理了 GET 和 POST 请求,GET 请求返回所有图书信息,POST 请求根据参数判断是添加、更新还是删除图书信息。 最后,我们可以编写一个 JSP 页面,展示所有图书信息,并提供表单来添加、更新和删除图书信息。例如: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>图书管理系统</title> </head> <body> <h1>图书列表</h1> <table border="1"> <tr> <th>图书号</th> <th>图书名</th> <th>作者</th> <th>价格</th> <th>操作</th> </tr> <c:forEach items="${books}" var="book"> <tr> <td>${book.id}</td> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> <td> <form action="${pageContext.request.contextPath}/book" method="post"> <input type="hidden" name="id" value="${book.id}"> <input type="hidden" name="action" value="update"> <input type="text" name="name" value="${book.name}"> <input type="text" name="author" value="${book.author}"> <input type="text" name="price" value="${book.price}"> <input type="submit" value="更新"> </form> <form action="${pageContext.request.contextPath}/book" method="post"> <input type="hidden" name="id" value="${book.id}"> <input type="hidden" name="action" value="delete"> <input type="submit" value="删除"> </form> </td> </tr> </c:forEach> </table> <h1>添加图书</h1> <form action="${pageContext.request.contextPath}/book" method="post"> <input type="hidden" name="action" value="add"> <label>图书名:</label><input type="text" name="name"><br> <label>作者:</label><input type="text" name="author"><br> <label>价格:</label><input type="text" name="price"><br> <input type="submit" value="添加"> </form> </body> </html> ``` 这个 JSP 页面展示了所有图书信息,并提供表单来添加、更新和删除图书信息。 最后,我们需要将这些组件组合在一起,例如在 web.xml 配置 ServletJSP 的映射关系: ```xml <servlet> <servlet-name>BookServlet</servlet-name> <servlet-class>com.example.BookServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BookServlet</servlet-name> <url-pattern>/book</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>book.jsp</welcome-file> </welcome-file-list> ``` 这个配置将 BookServlet 映射到 /book 路径,将 book.jsp 设置为默认欢迎页面。 这样,我们就完成了采用JavaBean+Servlet+JSP+DAO的Web架构设计的图书管理系统。您可以使用 Tomcat 等 Web 服务器来部署和运行这个系统,然后在浏览器访问 /book 路径来使用它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值