我是一名Java初学者,尝试使用Apache POI上传.xls
文件。该文件已完全上传,但不幸的是只有前两行插入数据库,我想要所有的行。我调试了代码,发现从第二行完成数据解析后会抛出错误:java.lang.IllegalStateException: Cannot forward after response has been committed
。
package com;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "upload";
private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("Request does not contain upload data");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
System.out.println("Uploaded at " + filePath);
// saves the file on disk
item.write(storeFile);
File file = new File(filePath);
InputStream input = new BufferedInputStream(new FileInputStream(file));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
//int i = 0;
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
List list = new ArrayList();
HSSFRow row = (HSSFRow)rows.next();
System.out.println("\n");
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell)cells.next();
if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
System.out.print(cell.getNumericCellValue() + " ");
list.add(cell.getNumericCellValue());
} else if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) {
System.out.print(cell.getStringCellValue() + " ");
list.add(cell.getStringCellValue());
} else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
System.out.print(cell.getBooleanCellValue() + " ");
list.add(cell.getBooleanCellValue());
} else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) {
System.out.print("BLANK ");
} else
System.out.print("Unknown cell type");
}
insertRowInDB(request,response,list);
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
}
public void insertRowInDB(HttpServletRequest request, HttpServletResponse response, List cellValues) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection con = null;
PreparedStatement psmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
psmt = (PreparedStatement)con.prepareStatement("INSERT INTO lillyTT" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
int paramIndex = 1;
for (Object cell : cellValues) {
psmt.setObject(paramIndex, cell);
paramIndex++;
}
int status = psmt.executeUpdate();
if (status > 0) {
System.out.println("successful");
RequestDispatcher rd = request.getRequestDispatcher("SelectOption.jsp");
rd.forward(request, response);
}
} catch(SQLException ex) {
ex.printStackTrace();
/* log the exception */
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
out.close();
psmt.close();
con.close();
} catch(SQLException ignored) {
}
}
}
}
答案 0 :(得分:1)
这是因为每次拨打insertRowInDB()
时,该方法都是使用PrintWriter
撰写回复,您只能发送一次响应。尝试删除它。