Servlet+Ajax实现对数据的列表展示(极简入门)

目录

1.准备工作

1.数据库源(这里以Mysql为例)

2.映射实体类

3.模拟三层架构(Dao、Service、Controller)

Dao接口

Dao实现

Service实现(这里省略Service接口)

Controller层(或叫Servlet层)

web.xml中注册该Servket


1.准备工作

1.数据库源(这里以Mysql为例)


    
      mysql
      mysql-connector-java
      5.1.47
    

因为是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)

Servlet+Ajax实现对数据的列表展示(极简入门)_第1张图片

(这是简单的表设计,大家可直接模拟一个,或自行创建一个表,只要实体类对应上即可)

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;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

3.模拟三层架构(Dao、Service、Controller)

Dao接口
public interface BookDao {

   // 书本列表
   public List bookList() throws SQLException, ClassNotFoundException;


}
Dao实现
public class BookDaoImpl implements BookDao {


    // 书本列表
    @Override
    public List bookList() throws SQLException, ClassNotFoundException {

        List books = new ArrayList();

        Connection connection = JdbcUtil2.getConnection();

        // 注意这里的JdbcUtil2是自己封装好的JDBC工具类

        Statement statement = JdbcUtil2.getStatement(connection);
        // 此处为了简便,不考虑sql注入,因此直接用statement而非prestatement

        ResultSet 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 getAllbooks() throws SQLException, ClassNotFoundException {

        BookDao bookDao = new BookDaoImpl();

        return bookDao.bookList();

    }
}
Controller层(或叫Servlet层)
public class BookServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List books = new ArrayList();

        BookService bookService = new BookService();

        try {
            books = bookService.getAllbooks();// 调用Service层,拿到books集合
            Gson gson = new GsonBuilder().create();
            // 转换为json
            String json = gson.toJson(books);
            // 设置响应类型,指定为json
            resp.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);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

}
web.xml中注册该Servket


  

  
  
    Content.jsp
   

 
    BookServket
    zhan.controller.BookServlet
  
  
  
    BookServket
    /BookServlet
  


编写Content.jsp(html+js+ajax)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    首页


    

列表展示

<%--该div用于列表展示--%> <%--引入jquery,用于调用ajax--%>

你可能感兴趣的:(servlet,ajax,前端)