Dao+Service+Servlet

Dao+Service+Servlet

1.加入依赖

数据库、连接池、工具类、jstl 页面使用

    <!-- 数据库 -->
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

        <!--连接池-->
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.9</version>
    </dependency>

    <!--通用增删改查的工具类依赖-->
    <!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
    <dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.6</version>
    </dependency>

    <!--jstl 页面使用-->
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

2.连接数据库

2.1 编写 jdbc.properties文件

url=jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
username=root
password=19990611
driver=com.mysql.cj.jdbc.Driver

解释
url数据库地址
//使用Unicode编码
useUnicode=true
//编码格式为utf8
characterEncoding=utf8
//时区为上海时间,也是东八区
//也可以写serverTimezone=GMT%2B8  %2B表示+号	GMT%2B8即为GMT+8	表示东八区,北京时间
serverTimezone=Asia/Shanghai	
//通过账号密码进行连接
useSSL=false
username数据库名称
password数据库密码
driver获取数据库连接

2.2 创建JdbcUtils类用来连接数据库和关闭操作

public class JdbcUtil {
    //配置DruidDataSource(德鲁伊)连接池
    private static DruidDataSource dataSource;

    static{
        try {
            //创建Properties对象
            Properties properties = new Properties();
            //读取jdbc.properties属性配置文件
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //从流中加载数据
            properties.load(inputStream);
            //创建数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取数据库连接池中的连接
     * @return  如果返回null,说明获取连接失败,有值就是成功
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            //连接数据库
            conn = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 关闭数据库的连接
     * @param connection
     */

    public static void closeConnection(Connection connection){
        try {
            if (connection != null){
                //关闭数据库
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

3.编写entity层

User实体类

public class User {
    private Integer id;
    private String name;
    private String password;
    private String email;

    public User() {
    }

    public User(Integer id, String name, String password, String email) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.email = email;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }

book实体类

public class Book {
    private Integer id;
    private String name;
    private double price;
    private String author;
    private Integer sales;
    private Integer stock;
    private String img_path;

    public Book() {
    }

    public Book(Integer id, String name, double price, String author, Integer sales, Integer stock, String img_path) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.author = author;
        this.sales = sales;
        this.stock = stock;
        this.img_path = img_path;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getSales() {
        return sales;
    }

    public void setSales(Integer sales) {
        this.sales = sales;
    }

    public Integer getStock() {
        return stock;
    }

    public void setStock(Integer stock) {
        this.stock = stock;
    }

    public String getImg_path() {
        return img_path;
    }

    public void setImg_path(String img_path) {
        this.img_path = img_path;
    }

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

4.编写dao层

4.1 BaseDao

public class BaseDao {
    //创建工具类中的增删改查的类
    QueryRunner runner = new QueryRunner();

    
    /**
     * 通用的增删改查的方法
     * @param sql	
     * @param args	
     * @return   返回的是执行sql语句成功的次数
     */
    public int update(String sql, Object... args) {
        //连接数据库
        Connection connection = JdbcUtil.getConnection();
        int count = 0;
        try {
            //调用通用的增删改查的方法
            count = runner.update(connection, sql, args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭数据库
            JdbcUtil.closeConnection(connection);
        }
        return count;
    }

    
    /**
     * 查询一个对象的方法
     * @param clazz
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T selectOne(Class<T> clazz,String sql,Object...args){
        //连接数据库
        Connection connection = JdbcUtil.getConnection();
        T t = null;
        try {
            //调用查询一个对象的方法
            t = runner.query(connection, sql, new BeanHandler<T>(clazz), args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭数据库
            JdbcUtil.closeConnection(connection);
        }
        return t;
    }


    /**
     * 查询所有对象的方法
     * @param clazz
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> List<T> selectAll(Class<T> clazz, String sql, Object...args){
        //连接数据库
        Connection connection = JdbcUtil.getConnection();
        //创建一个list放对象
        List<T> list = new ArrayList<>();
        try {
            //调用查询所有对象的方法
            list = runner.query(connection, sql, new BeanListHandler<T>(clazz), args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭数据库
            JdbcUtil.closeConnection(connection);
        }
        return list;
    }
}

4.2 UserDao 和 BookDao

编写UserDao 和 BookDao的增删改查的接口方法

UserDao

public interface UserDao {
    //增加
    public int insertUser(User user);
    //删除
    public int deleteUserById(Integer id);
    //修改
    public int updateUser(User user);
    //查询一个
    public User selectUserOneById(Integer id);
    //查询所有
    public List<User> selectUserAll();
}

BookDao

public interface BookDao {
    //增加
    public int insertBook(Book book);
    //删除
    public int deleteBookById(Integer id );
    //修改
    public int updateBook(Book book);
    //查询一个
    public Book selectBookOneById(Integer id);
    //查询所有
    public List<Book> selectBookAll();
}

4.3 UserDaoImpl和BookDaoImpl

编写实现UserDao 和 BookDao接口的UserDaoImpl和BookDaoImpl,同时继承BaseDao

UserDaoImpl

public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public int insertUser(User user) {
        String sql = "insert into user(name,password,email)values(?,?,?)";

        return update(sql,user.getName(),user.getPassword(),user.getEmail());
    }

    @Override
    public int deleteUserById(Integer id) {
        String sql = "delete from user where id=?";

        return update(sql,id);
    }

    @Override
    public int updateUser(User user) {
        String sql = "update user set name=?,password=?,email=? where id=?";

        return update(sql,user.getName(),user.getPassword(),user.getEmail(),user.getId());
    }

    @Override
    public User selectUserOneById(Integer id) {
        String sql = "select * from user where id=?";
        return selectOne(User.class,sql,id);
    }

    @Override
    public List<User> selectUserAll() {
        String sql = "select * from user ";
        return selectAll(User.class,sql);
    }
}

BookDaoImpl

public class BookDaoImpl extends BaseDao implements BookDao {

    @Override
    public int insertBook(Book book) {
        String sql = "insert into book(name,price,author,sales,stock,img_path)values(?,?,?,?,?,?)";
        return update(sql,book.getName(),book.getPrice(),book.getAuthor(),book.getSales(),book.getStock(),book.getImg_path());
    }

    @Override
    public int deleteBookById(Integer id) {
        String sql = "delete from book where id=?";
        return update(sql,id);
    }

    @Override
    public int updateBook(Book book) {
        String sql = "update book set name=?,price=?,author=?,sales=?,stock=?,img_path=? where id=?";
        return update(sql,book.getName(),book.getPrice(),book.getAuthor(),book.getSales(),book.getStock(),book.getImg_path(),book.getId());
    }

    @Override
    public Book selectBookOneById(Integer id) {
        String sql = "select * from book where id=?";
        return selectOne(Book.class,sql,id);
    }

    @Override
    public List<Book> selectBookAll() {
        String sql = "select * from book ";
        return selectAll(Book.class,sql);
    }
}

5.编写service层

service层(业务层):业务层里面主要封装的是一些业务功能是由对DAO的一次到多次的调用来完成

5.1 UserService和BookService

编写UserService和BookService接口,写增删改查接口方法.

UserService

public interface UserService {
    public void insertUser(User user);

    public void deleteById(Integer id);

    public void updateUser(User user);

    public User selectOneById(Integer id);

    public List<User> selectAllUser();
}

BookService

public interface BookService {
    public void insertBook(Book book);

    public void deleteBookById(Integer id);

    public void updateBook(Book book);

    public Book selectBookOneById(Integer id);

    public List<Book> selectBookAll();
}

5.2 UserServiceImpl和BookServiceImpl

编写实现UserService和 BookService接口的UserServiceImpl和BookServiceImpl

UserServiceImpl

public class UserServiceImpl implements UserService {
    //创建userDao对象
    UserDao userDao = new UserDaoImpl();

    @Override
    public void insertUser(User user) {
        userDao.insertUser(user);
    }

    @Override
    public void deleteById(Integer id) {
        userDao.deleteUserById(id);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public User selectOneById(Integer id) {
        return userDao.selectUserOneById(id);
    }

    @Override
    public List<User> selectAllUser() {
        return userDao.selectUserAll();
    }
    
}

BookServiceImpl

public class BookServiceImpl implements BookService {
    BookDao bookDao = new BookDaoImpl();

    @Override
    public void insertBook(Book book) {
        bookDao.insertBook(book);
    }

    @Override
    public void deleteBookById(Integer id) {
        bookDao.deleteBookById(id);
    }

    @Override
    public void updateBook(Book book) {
        bookDao.updateBook(book);
    }

    @Override
    public Book selectBookOneById(Integer id) {
        return bookDao.selectBookOneById(id);
    }

    @Override
    public List<Book> selectBookAll() {
        return bookDao.selectBookAll();
    }
    
}

5.编写servlet层

5.1 BaseServlet

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用UTF-8编码格式
        req.setCharacterEncoding("UTF-8");
        //获取表单里方法的名字
        String action = req.getParameter("action");

        try {
            
            //getDeclaredMethod 当前的类获取的方法名
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);//这里的this指的是继承BaseServlet对象
            //执行这个对象的目标方法
            method.invoke(this,req,resp);

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

}

5.2 编写UserServlet和BookServlet

UserServlet

public class UserServlet extends BaseServlet{

   /**
    * 登陆
    * @param req
    * @param resp
    * @throws ServletException
    * @throws IOException
    */
   protected void loginUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String name = req.getParameter("name");
       String password = req.getParameter("password");

       UserDaoImpl userDao = new UserDaoImpl();
       User login = userDao.login(name, password);
       if (login == null){
           req.getRequestDispatcher("登陆页面.jsp").forward(req,resp);
       }else{
           req.getRequestDispatcher("SelectBookAllServlet").forward(req,resp);

       }
   }

   /**
    * 注册,就是增加
    * @param req
    * @param resp
    * @throws ServletException
    * @throws IOException
    */
   protected void registerUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       //1.获取用户从表单输入的值
       String name = req.getParameter("name");
       String password = req.getParameter("password");
       String email = req.getParameter("email");

       //2.调用service中增加的方法
       UserService userService = new UserServiceImpl();
       userService.insertUser(new User(null, name, password, email));

       //3.转发到UserListServlet
       req.getRequestDispatcher("登陆页面.jsp").forward(req, resp);
   }


   protected void selectUserOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       //获取传入的需要删除的数据  id
       String id = req.getParameter("id");

       //调用service中删除的方法
       UserService userService = new UserServiceImpl();
       User user = userService.selectOneById(Integer.parseInt(id));

       //获取取得的对象给update.jsp
       req.setAttribute("user",user);
       req.getRequestDispatcher("updateUser.jsp").forward(req,resp);
   }


   protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //1.获取update.jsp里的值
       String id = req.getParameter("id");
       String name = req.getParameter("name");
       String password = req.getParameter("password");
       String email = req.getParameter("email");

       //2.调用service中修改的方法
       UserService userService = new UserServiceImpl();
       userService.updateUser(new User(Integer.parseInt(id),name,password,email));
       //3.转发到UserListServlet
       req.getRequestDispatcher("/UserListServlet").forward(req,resp);
   }

   protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //1.获取传入的需要删除的数据  id
       String id = req.getParameter("id");

       //2.调用service中删除的方法
       UserService userService = new UserServiceImpl();
       userService.deleteById(Integer.parseInt(id));

       //3.跳转到UserListServlet
       req.getRequestDispatcher("/UserListServlet").forward(req,resp);
   }
}

BookServlet

public class BookServlet extends BaseServlet{
    /**
     * 增加图书信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void insertBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取写入的值
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String author = req.getParameter("author");
        String sales = req.getParameter("sales");
        String stock = req.getParameter("stock");
        String img_path = req.getParameter("img_path");
        //调用service增加方法
        BookService bookService = new BookServiceImpl();
        bookService.insertBook(new Book(null,name,Double.parseDouble(price),author,Integer.parseInt(sales),Integer.parseInt(stock),img_path));
        //转发到SelectBookAllServlet
        req.getRequestDispatcher("/SelectBookAllServlet").forward(req,resp);
    }

    /**
     * 删除图书信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取需要删除的id
        String id = req.getParameter("id");
        //调用方法
        BookService bookService = new BookServiceImpl();
        bookService.deleteBookById(Integer.parseInt(id));
        //转发到SelectBookAllServlet
        req.getRequestDispatcher("/SelectBookAllServlet").forward(req,resp);
    }

    /**
     * 修改一个图书的信息要先进行对要修改的这个图书的id进行查询
     * 在转到/updateBook.jsp修改图书的页面
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void selectBookOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取id
        String id = req.getParameter("id");
        //调用方法
        BookService bookService = new BookServiceImpl();
        Book book = bookService.selectBookOneById(Integer.parseInt(id));
        //将获取到的对象给updateBook.jsp
        req.setAttribute("book",book);
        req.getRequestDispatcher("/updateBook.jsp").forward(req,resp);
    }

    /**
     * 修改图书信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取值
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String author = req.getParameter("author");
        String sales = req.getParameter("sales");
        String stock = req.getParameter("stock");
        String img_path = req.getParameter("img_path");
        //调用修改方法
        BookService bookService = new BookServiceImpl();
        bookService.updateBook(new Book(Integer.parseInt(id),name,Double.parseDouble(price),author,Integer.parseInt(sales),Integer.parseInt(stock),img_path));
        //转发到SelectBookAllServlet
        req.getRequestDispatcher("/SelectBookAllServlet").forward(req,resp);
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值