package foodOnline.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 foodOnline.dao.FoodDao;
import foodOnline.dao.impl.FoodDaoImpl;
import foodOnline.entity.Food;
//49行categoryId報錯說轉換異常,看了老半天也改了還是說錯誤
public class addServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
String chineseName=null;
String englishName=null;
String description=null;
String filename=null;
int categoryId=0;
try {
List<FileItem>list=upload.parseRequest(request);
for(FileItem item:list){
if(item.isFormField()){
if("chineseName".equals(item.getFieldName())){
chineseName=item.getString("UTF-8");
}else if("englishName".equals(item.getFieldName())){
englishName=item.getString("UTF-8");
}else if("description".equals(item.getFieldName())){
description=item.getString("UTF-8");
}else if("categoryId".equals(item.getFieldName())){
categoryId = Integer.parseInt(item.getString());
}
}else{
String clientFilename=item.getName();
String ext = clientFilename.substring(clientFilename
.lastIndexOf("."));
filename = englishName + ext;
ServletContext application=request.getSession().getServletContext();
String filepath=application.getRealPath("images/menus/"+filename);
item.write(new File(filepath));
}
}
if(chineseName!=null&&englishName!=null&&description!=null&&categoryId!=0){
Food food=new Food(0,chineseName,englishName,categoryId,description);
FoodDao fd=new FoodDaoImpl();
fd.addFoods(food);
response.sendRedirect("food/admin/foodsListServlet");
}else{
request.getRequestDispatcher("error.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
}
然後現在出現新的錯誤,
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '??…è’???—é??' for key 'ChineseName'
categoryId = Integer.parseInt(item.getString());
你把item.getString() 這個東西輸出,看一下是不是純數字的字符串