在批量新增里如何循环获取里面多个新增book的值?

在批量新增里如何循环获取里面多个新增book的值?

作业里用了js脚本把多个book拼接到一个表单里,我怎样才能获取多个book,然后再创建list把他们保存起来?

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
慕布斯645313 2019-02-27 19:01:37

你看一下我写的源码吧

package com.imooc.book.servlet;

import com.imooc.book.entity.Book;
import com.imooc.book.entity.Category;
import com.imooc.book.service.BookService;
import com.imooc.book.service.CategoryService;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * 图书Servlet
 *
 * @version 1.0
 */
public class BookServlet extends HttpServlet {

    private BookService bookService;

    private CategoryService categoryService;

    @Override
    public void init() throws ServletException {
        super.init();
        bookService = new BookService();
        categoryService = new CategoryService();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if ("/book/list.do".equals(req.getServletPath())) {
            String categoryIdStr = req.getParameter("categoryId");
            try {
                Long catgoryId = null;
                if (null != categoryIdStr) {
                    catgoryId = Long.valueOf(categoryIdStr);
                }
                List<Book> books = bookService.getBooksByCategoryId(catgoryId, 1, 5000);
                req.setAttribute("books", books);

                List<Category> categories = categoryService.getCateegories();
                req.setAttribute("categories", categories);
                req.getRequestDispatcher("/WEB-INF/views/biz/book_list.jsp").forward(req, resp);
            } catch (NumberFormatException e) {
                req.getRequestDispatcher("/WEB-INF/views/biz/book_list.jsp").forward(req, resp);
            }
        } else if ("/book/addPrompt.do".equals(req.getServletPath())) {
            List<Category> categories = categoryService.getCateegories();
            req.setAttribute("categories", categories);
            req.getRequestDispatcher("/WEB-INF/views/biz/add_book.jsp").forward(req, resp);
        } else if ("/book/add.do".equals(req.getServletPath())) {
            req.setCharacterEncoding("utf-8");
            if (ServletFileUpload.isMultipartContent(req)) {
                try {
                    FileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(req);//解析请求
                    Iterator<FileItem> ite = items.iterator();
                    List<Book> books = new ArrayList<Book>();
                    Book book = new Book();
                    int index = 0;
                    while (ite.hasNext()) {
                        if (index != 0 && index % 5 == 0) {
                            books.add(book);
                            book = new Book();
                        }
                        index++;
                        FileItem item = ite.next();
                        if (item.isFormField()) {//信息是普通的格式
                            String fieldName = item.getFieldName();
                            if ("categoryId".equals(fieldName)) {
                                book.setCategoryId(Long.valueOf(item.getString()));
                            } else if ("level".equals(fieldName)) {
                                book.setLevel(Integer.valueOf(item.getString()));
                            } else if ("name".equals(fieldName)) {
                                book.setName(new String(item.getString().getBytes("iso8859-1"), "utf-8"));
                            } else if ("price".equals(fieldName)) {
                                book.setPrice(Integer.valueOf(item.getString()));
                            }
                        } else {//信息是文件格式
                            book.setImg(item.get());
                        }
                    }
                    books.add(book);
                    for (Book book1 : books) {
                        saveImg(book1);
                        bookService.addBook(book1);
                    }
                    req.getRequestDispatcher("/book/list.do").forward(req, resp);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String IMG_PARENT_PATH = "/Projects/Homework/Book/IMG_PARENT/";

    private void saveImg(Book book) throws IOException {
        String path = IMG_PARENT_PATH + book.getName() + ".jpg";
        ImageIO.write(ImageIO.read(new ByteInputStream(book.getImg(), book.getImg().length)), 
                "jpg", new File(path));
        book.setImgPath(path);
    }

    @Override
    public void destroy() {
        super.destroy();
        bookService = null;
        categoryService = null;
    }

}


一叶知秋519 2018-06-14 11:46:48

因为多个Book时,Book相同属性的input框对应的name是相同的,提交表单以后,在Servlet中获取数据时,可以通过这种方式来进行获取:

String[] names = request.getParameterValues("name");

String[] categoryIds = request.getParameterValues("categoryId");

即直接获取数组,然后在进行遍历添加就可以了。

祝学习愉快!

  • huachun #1
    那获取图片文件信息该怎么操作啊,用什么方法啊
    2019-02-27 17:41:04
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
SSM主流框架入门与综合项目实战2018版
  • 参与学习           人
  • 提交作业       205    份
  • 解答问题       4317    个

Java中非常实用的SSM整合开发内容,从Spring开始,到MyBaits的进阶内容,再到SpringMVC的应用,最后是SSM整合开发案例,逐步深入,助你成长为一名Java工程师!

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师