javawebday64_3(book 上传文件校验 工厂)

cart用map
category在book中是cid没有具体的分类名称 需要toBean
order使用事务
user  uuid

bookstore.book.domain.Book

    private String bid;
    private String bname;
    private double price;
    private String author;
    private String image;
    private Category category;
    private boolean del;
    public boolean isDel() {
        return del;
    }
    public void setDel(boolean del) {
        this.del = del;
    }

BookDao

public class BookDao {
    private QueryRunner qr = new TxQueryRunner();
    /**
     * 查询所有图书
     * @return
     */
    public List<Book> findAll(){
        try{
            String sql = "select * from book where del=false";
            return qr.query(sql, new BeanListHandler<Book>(Book.class));
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 按分类查询
     * @param cid
     * @return
     */
    public List<Book> findByCategory(String cid) {
        try{
            String sql = "select * from book where cid=? and del=false";
            return qr.query(sql, new BeanListHandler<Book>(Book.class),cid);
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 加载方法
     * @param bid
     * @return
     */
    public Book finyByBid(String bid) {
        try{
            /*
             * 需要在Book对象中保存Category的信息
             */
            String sql = "select * from book where bid=?";
            Map<String,Object> map = qr.query(sql, new MapHandler(),bid);
            /*
             * 使用一个Map,映射出两个对象,再给这两个对象建立关系
             */
            Category category = CommonUtils.toBean(map, Category.class);
            Book book = CommonUtils.toBean(map, Book.class);
            book.setCategory(category);
            return book;
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 查询指定分类下的图书本书
     * @param cid
     * @return
     */
    public int getCountByCid(String cid) {
        try{
            String sql = "select count(*) from book where cid=?";
            Number cnt = (Number) qr.query(sql, new ScalarHandler(),cid);
            return cnt.intValue();
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加图书
     * @param book
     */
    public void add(Book book) {
        try{
            String sql = "insert into book values(?,?,?,?,?,?,?)";
            Object[] params = {book.getBid(),book.getBname(),book.getPrice(),
                    book.getAuthor(),book.getImage(),book.getCategory().getCid(),0
                    };
            qr.update(sql,params);
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除图书
     * @param bid
     */
    public void delete(String bid){
        try{
            String sql = "update book set del=true where bid=?";
            qr.update(sql,bid);
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }

    public void edit(Book book) {
        try{
            String sql = "update book set bname=?,price=?,author=?,image=?,cid=? where bid=?";
            //可以直接更改插入String字符串 中文保留 不乱码 因此是book.getBname的问题
            Object[] params = {book.getBname(),book.getPrice(),
                    book.getAuthor(),book.getImage(),book.getCategory().getCid(),book.getBid()
                    };
            qr.update(sql,params);
        } catch(SQLException e){
            throw new RuntimeException(e);
        }   
    }
}

BookService

public class BookService {
    private  BookDao bookDao = new BookDao();
    /**
     * 查询所有图书
     * @return
     */
    public List<Book> findAll(){
        return bookDao.findAll();
    }
    /**
     * 分类查询
     * @param cid
     * @return
     */
    public List<Book> findByCategory(String cid) {
        return bookDao.findByCategory(cid);
    }
    public Book load(String bid) {

        return bookDao.finyByBid(bid);
    }

    /**
     * 添加图书
     */
    public void add(Book book) {
        bookDao.add(book);
    }

    public void delete(String bid){
        bookDao.delete(bid);
    }
    public void edit(Book book) {
        bookDao.edit(book);
    }
}
public class BookServlet extends BaseServlet {
    private BookService bookService = new BookService();
    public String load(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
         * 1、得到参数bid
         * 2、查询得到book
         * 3、保存,转发到desc.jsp
         */
        request.setAttribute("book", bookService.load(request.getParameter("bid")));
        return "f:jsps/book/desc.jsp";
    }
    /**
     * 查询所有图书
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("bookList", bookService.findAll());
        return "f:/jsps/book/list.jsp";
    }
    /**
     * 按分类查询
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String findByCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid =request.getParameter("cid");
        request.setAttribute("bookList", bookService.findByCategory(cid));
        return "f:/jsps/book/list.jsp";
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        /*
         * 1、把表单数据封装到Book对象中
         *  上传三步
         */
        //创建工厂
        DiskFileItemFactory factory = new DiskFileItemFactory(50*1024,new File("H:/f/temp"));
        //得到解析器
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //设置单个文件大小为50kb
        sfu.setFileSizeMax(50*1024);
        //使用解析器解析request对象,得到List<FileItem>
        try {
            List<FileItem> fileItemList = sfu.parseRequest(request);
            /*
             * 把fileItemList中的数据封装到Book对象中
             *  把所有的普通表单字段数据先封装到Map中
             *  再把map中的数据封装到Book对象中
             */
//          fileItemList.get(0).isFormField();//如果false就是file
            Map<String,String> map = new HashMap<String, String>();
            for(FileItem fileItem:fileItemList){
                if(fileItem.isFormField()){
                map.put(fileItem.getFieldName(),fileItem.getString("utf-8"));
                }
            }
            Book book = CommonUtils.toBean(map, Book.class);
            //为book指定bid
            book.setBid(CommonUtils.uuid());
            /*
             * 需要把Map中的cid封装到Category对象中,再把Category赋给Book
             */
            Category category = CommonUtils.toBean(map, Category.class);
            book.setCategory(category);
            /*
             * 2、保存上传的文件
             *  保存的路径【目录】
             *  保存的文件名称 
             */
            //得到保存的目录
            String savepath = this.getServletContext().getRealPath("/book_img");
            //得到文件名称,给原来文件名称添加uuid前缀。避免文件名冲突
            String filename = CommonUtils.uuid()+"_"+fileItemList.get(1).getName();
            /*
             * 校验文件的扩展名
             */
            if(!filename.toLowerCase().endsWith("jpg")){
                request.setAttribute("msg", "上传的图片不是jpg扩展名");
                request.setAttribute("categoryList", categoryService.findAll());
                request.getRequestDispatcher("/adminjsps/admin/book/add.jsp")
                    .forward(request, response);
                return;
            }
            //使用目录和文件名称创建目标文件
            File destFile = new File(savepath,filename);
            //保存上传文件到目标文件位置
            fileItemList.get(1).write(destFile);
            /*
             * 3、设置Book对象的image,即把图片的路径设置给Book的image
             */
            book.setImage("book_img/"+filename);

            /*
             * 4、使用BookService完成保存
             */
            bookService.add(book);

            /*
             * 校验图片的尺寸
             */
            Image image =  new ImageIcon(destFile.getAbsolutePath()).getImage();
            if(image.getWidth(null)>200 || image.getHeight(null)>200){
                destFile.delete();//删除这个文件
                request.setAttribute("msg", "上传的图片尺寸超出了200*200");
                request.setAttribute("categoryList", categoryService.findAll());
                request.getRequestDispatcher("/adminjsps/admin/book/add.jsp")
                    .forward(request, response);
            }
            /*
             * 5、返回到图书列表
             */
            request.getRequestDispatcher("/admin/AdminBookServlet?method=findAll")
                .forward(request, response);;
        } catch (Exception e) {
            if(e instanceof FileUploadBase.FileSizeLimitExceededException){
                request.setAttribute("msg", "文件大于50kb");
                request.getRequestDispatcher("/adminjsps/admin/book/add.jsp")
                    .forward(request, response);
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值