目录
1.准备工作
1.数据库源(这里以Mysql为例)
2.映射实体类
3.模拟三层架构(Dao、Service、Controller)
Dao接口
Dao实现
Service实现(这里省略Service接口)
Controller层(或叫Servlet层)
web.xml中注册该Servket
1.准备工作
1.数据库源(这里以Mysql为例)
<!-- 数据库依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency>
因为是Servlet项目,所以要用到JDBC去连接后台数据库,此处还不熟悉的可借鉴我前几篇有关JDBC的文章
这里直接给出工具类JdbcUtil2:
public class JdbcUtil2 {private static String url;private static String username;private static String password;private static String driver;static {InputStream is = JdbcUtil2.class.getClassLoader().getResourceAsStream("db.properties");Properties pro = new Properties();try {pro.load(is);} catch (IOException e) {throw new RuntimeException(e);}url = pro.getProperty("url");username = pro.getProperty("username");password = pro.getProperty("password");driver = pro.getProperty("driver");}public static Connection getConnection() throws SQLException, ClassNotFoundException {Class.forName(driver); // 显示加载驱动return (Connection) DriverManager.getConnection(url,username,password); // 拿到连接}public static Statement getStatement(Connection connection) throws SQLException {Statement statement = connection.createStatement();return statement;}public static ResultSet getResultSet(Statement statement) throws SQLException {ResultSet resultSet = statement.executeQuery("select * from book");return resultSet;}public static void close(Connection connection,Statement statement,ResultSet resultSet) throws SQLException {if(resultSet!=null){resultSet.close();resultSet = null;}if(statement!=null){statement.close();statement = null;}if(connection!=null){connection.close();connection = null;}}public static void main(String[] args) throws SQLException, ClassNotFoundException {Connection connection = JdbcUtil2.getConnection();Statement statement = JdbcUtil2.getStatement(connection);ResultSet resultSet = JdbcUtil2.getResultSet(statement);while(resultSet.next()){int id = resultSet.getInt("id");String name = resultSet.getString("name");double price = resultSet.getDouble("price");System.out.println("id="+id+",name="+name+",price="+price);}JdbcUtil2.close(connection,statement,resultSet);}
}
2.映射实体类
(这里我对应的数据库表是Book,所以创建实体类Book)
(这是简单的表设计,大家可直接模拟一个,或自行创建一个表,只要实体类对应上即可)
public class Book {private int id;private String name;private double price;public Book(int id, String name, double price) {this.id = id;this.name = name;this.price = price;}public Book() {}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "Book{" +"id=" + id +", name='" + name + '\'' +", price=" + price +'}';}
}
3.模拟三层架构(Dao、Service、Controller)
Dao接口
public interface BookDao {// 书本列表public List<Book> bookList() throws SQLException, ClassNotFoundException;}
Dao实现
public class BookDaoImpl implements BookDao {// 书本列表@Overridepublic List<Book> bookList() throws SQLException, ClassNotFoundException {List<Book> books = new ArrayList<Book>();Connection connection = JdbcUtil2.getConnection();// 注意这里的JdbcUtil2是自己封装好的JDBC工具类Statement statement = JdbcUtil2.getStatement(connection);// 此处为了简便,不考虑sql注入,因此直接用statement而非prestatementResultSet resultSet = JdbcUtil2.getResultSet(statement);// 获取结果集while(resultSet.next()){// 循环拿到每本书的信息,并存在每个新创建的book对象中Book book = new Book();book.setId(resultSet.getInt("id"));book.setName(resultSet.getString("name"));book.setPrice(resultSet.getDouble("price"));books.add(book);// 添加每本书本信息在集合}return books; // 返回该集合}}
Service实现(这里省略Service接口)
public class BookService {public List<Book> getAllbooks() throws SQLException, ClassNotFoundException {BookDao bookDao = new BookDaoImpl();return bookDao.bookList();}
}
Controller层(或叫Servlet层)
public class BookServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {List<Book> books = new ArrayList<Book>();BookService bookService = new BookService();try {books = bookService.getAllbooks();// 调用Service层,拿到books集合Gson gson = new GsonBuilder().create();// 转换为jsonString json = gson.toJson(books);// 设置响应类型,指定为jsonresp.setContentType("application/json");// 指定字符集resp.setCharacterEncoding("UTF-8");// 返回数据resp.getWriter().write(json);} catch (SQLException e) {throw new RuntimeException(e);} catch (ClassNotFoundException e) {throw new RuntimeException(e);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}}
web.xml中注册该Servket
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><!--设置首页--><welcome-file-list><welcome-file>Content.jsp</welcome-file></welcome-file-list> <servlet><servlet-name>BookServket</servlet-name><servlet-class>zhan.controller.BookServlet</servlet-class></servlet><servlet-mapping><servlet-name>BookServket</servlet-name><url-pattern>/BookServlet</url-pattern></servlet-mapping></web-app>
编写Content.jsp(html+js+ajax)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>首页</title>
</head>
<body><h3>列表展示</h3><button id="listButton">书本信息列表</button><div id="bookList"></div><%--该div用于列表展示--%></body><%--引入jquery,用于调用ajax--%>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script><script>$(function (){$("#listButton").click(function (){$.ajax({url: "http://localhost:8080/BookServlet",type: "GET",success: function (response){ // 一般来说,response对响应体内容的封装,我们可以从中获取值var bookList = $("#bookList");bookList.empty(); // 清空列表response.forEach(function(book) {bookList.append("id:"+book.id+",name:"+book.name+",price"+book.price+"<br>");// 在response响应中遍历获取到的列表,以book为单位,不断填充在bookList这个div中 });},error: function (xhr, status, error) {alert("服务器异常!");}});});});
</script>