javaWeb设计模式

>开发模式
1、JSP + JavaBean  在网页中new类的实例  在servlet中封装会比较好
      在网页中写逻辑就会很乱     只适合教学使用。


2、MVC设计模式
JSP + Servlet + JavaBean 
MVC:开发模式
M: Model模型 JavaBean|四种作用域
V:view视图 JSP
C:Controller控制器 Servlet

MVC

JSP + Servlet + JavaBean (可以把javaBean当做四个域对象)
MVC:开发模式
M: Model模型 JavaBean|四种作用域
V:view视图 JSP
C:Controller控制器 Servlet
约定优于编码


>开发步骤
开发时的注意事项:
  约定大于编码。数据库表中的字段名要实体类中的属性名一致。
1、创建数据库及表。

2、编写web应用
2.1搭建开发环境,添加jar包等

cn.itcast.domain:实体类
cn.itcast.service:业务接口
cn.itcast.service.impl:业务实现类
cn.itcast.dao:数据访问接口
cn.itcast.dao.impl:数据访问实现类
cn.itcast.web.servlet
web:jsp

2.2创建实体类(javabean)
注意:
1)实现Serializable接口,以实现序列化,反序列化。
2)添加空参的构造函数。

public class Book implements Serializable{
    private String id;
    private String name;
    private double price;
    private int pnum;
    private String category;
    private String description;
    
    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", price=" + price + ", pnum=" + pnum + ", category=" + category
                + ", description=" + description + "]";
    }
    
    
    public String getId() {
        return id;
    }
    public void setId(String 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;
    }
    public int getPnum() {
        return pnum;
    }
    public void setPnum(int pnum) {
        this.pnum = pnum;
    }
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    
}
View Code


2.3service层(业务层)--接口

service实现类:

public class BookServiceImpl {  //在service层接收异常
    //创建一个BookDao对象
    BookDaoImpl bookDaoImpl = new BookDaoImpl();

    public List<Book> findAllBooks()  {
        try {
            return bookDaoImpl.findAllBooks();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void addBook(Book book) {
        try {
            bookDaoImpl.addBook(book);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Book findBookById(String id) {
        try {
            return bookDaoImpl.findBookById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void updateBook(Book book) {
        try {
            bookDaoImpl.updateBook(book);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteBook(String id) {
        try {
            bookDaoImpl.deleteBook(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteAllBooks(String[] ids) {
        try {
            bookDaoImpl.deleteAllBooks(ids);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<Book> searchBooks(String id, String category, String name, String minprice, String maxprice) {
        try {
            return bookDaoImpl.searchBooks(id,category,name,minprice,maxprice);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public PageBean finBooksPage(int currentPage, int pageSize) {
        try {
            int count;
            count = bookDaoImpl.count();
            List<Book> booksList = bookDaoImpl.findBooks(currentPage,pageSize);
            int totalPages = (int) Math.ceil(count*1.0/pageSize);
            
            //把5个变量封装到PageBean中
            PageBean pb = new PageBean();
            pb.setBooksList(booksList);
            pb.setCount(count);
            pb.setCurrentPage(currentPage);
            pb.setPageSize(pageSize);
            pb.setTotalPages(totalPages);
            
            return pb;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;        
    }        
}
View Code

2.3dao数据访问层--接口

dao实现类:
添加数据库连接等相关工具类jar包:DBUtils、Spring Template
进行增删改查的操作。

public class BookDaoImpl {
    
    /**
     * 查找所有的图书
     * @return
     * @throws SQLException
     */
    public List<Book> findAllBooks() throws SQLException{
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        return qr.query("select * from books", new BeanListHandler<Book>(Book.class));
    }

    /**
     * 添加一本图书到数据库中
     * @param book  要添加的图书对象
     * @throws SQLException 
     */
    public void addBook(Book book) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        qr.update("INSERT INTO books VALUES(?,?,?,?,?,?);", book.getId(),book.getName(),book.getPrice(),book.getPnum(),book.getCategory(),book.getDescription());
    }

    /**根据图书的id,找到对应的对象
     * @param id 图书的id
     * @return  对应id的图书对象  
     * @throws SQLException
     */
    public Book findBookById(String id) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        return qr.query("select * from books where id=?", new BeanHandler<Book>(Book.class),id);
    }

    /** 根据图书对象更新数据库
     * @param book  图书对象
     * @throws SQLException
     */
    public void updateBook(Book book) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        int i = qr.update("update books set name=?,price=?,pnum=?,category=?,description=? where id=?", 
                book.getName(),book.getPrice(),book.getPnum(),book.getCategory(),book.getDescription(),book.getId());
        System.out.println(i>0?"更新成功":"更新失败");
    }

    /**从数据库中删除指定id的图书
     * @param id  图书的id
     * @throws SQLException 
     */
    public void deleteBook(String id) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        qr.update("delete from books where id=?", id);
    }
    
    /**批量删除ids数组中的id
     * @param ids
     * @throws SQLException 
     */
    public void deleteAllBooks(String[] ids) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        Object[][] params = new Object[ids.length][];
        for (int i = 0; i < params.length; i++) {
            params[i] = new Object[] {ids[i]};
        }
        qr.batch("delete from books where id=?", params);
    }

    /**多条件查询图书
     * @param id
     * @param category
     * @param name
     * @param minprice
     * @param maxprice
     * @return 
     * @throws SQLException 
     */
    public List<Book> searchBooks(String id, String category, String name, String minprice, String maxprice) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        String sql = "select * from books where 1=1";  //因为下面用到的参数是Object类型,这里不必加泛型
        List list = new ArrayList<>();

        if(!"".equals(id.trim())){   //==》空格也是字符
            sql+=" and id like ?"; //  不能在这写%   %'1002'%
            list.add("%"+id.trim()+"%");// '%1002%'
        }
        
        if(!"".equals(name.trim())) {
            sql+=" and name like ?";
            list.add(name.trim());
        }
        if(!"".equals(category.trim())) {
            sql+=" and category=?";
            list.add(category.trim());
        }
        if(!"".equals(minprice.trim())) {
            sql+=" and price>= ?";
            list.add(minprice.trim());
        }
        if(!"".equals(maxprice.trim())) {
            sql+=" and price<= ?";
            list.add(maxprice.trim());
        }
//        System.out.println(list);
//        System.out.println(sql);
//        System.out.println(minprice);
//        System.out.println(maxprice);
        return qr.query(sql, new BeanListHandler<Book>(Book.class),list.toArray());
    }

    /**
     * @return  数据库中图书的总记录数
     * @throws SQLException
     */
    public int count() throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        long l = (Long) qr.query("select count(*) from books", new ScalarHandler(1));
        return (int)l;
    }

    /**找到分页的数据
     * @param currentPagez
     * @param pageSize
     * @return
     * @throws SQLException 
     */
    public List<Book> findBooks(int currentPage, int pageSize) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        return qr.query("select * from books limit ?,?", new BeanListHandler<Book>(Book.class),(currentPage-1)*pageSize,pageSize);
    }    
}
View Code


2.4表示层(JSP、Servlet(负责整体逻辑的控制))


posted @ 2018-12-03 14:39  payn  阅读(325)  评论(0)    收藏  举报