List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:controller.servlet.PostServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//w w w . j a v a 2 s. co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PostDAOService postService = PostDAO.getInstance(); String title = null; String shortTitle = null; String sCategoryID = null; String content = null; String link = null; String action = null; // String pathImage; String imageName = ""; boolean isUploadSuccess = false; ServletFileUpload fileUpload = new ServletFileUpload(); try { FileItemIterator itr = fileUpload.getItemIterator(request); while (itr.hasNext()) { FileItemStream fileItemStream = itr.next(); if (fileItemStream.isFormField()) { String fieldName = fileItemStream.getFieldName(); InputStream is = fileItemStream.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b, "UTF-8"); if (fieldName.equals("action")) { action = value; } if (fieldName.equals("title")) { title = value; } if (fieldName.equals("content")) { content = value; } if (fieldName.equals("short-title")) { shortTitle = value; } if (fieldName.equals("category-id")) { sCategoryID = value; } if (fieldName.equals("link")) { link = value; } } else { String realPath = getServletContext().getRealPath("/"); String filePath = realPath.replace("\\build\\web", "\\web\\image\\post");//Duong dan luu file anh imageName = fileItemStream.getName(); StringTokenizer token = new StringTokenizer(imageName, "."); String fileNameExtension = ""; while (token.hasMoreElements()) { fileNameExtension = token.nextElement().toString(); } System.out.println("img: " + imageName); if (!imageName.equals("")) { imageName = Support.randomString(); isUploadSuccess = FileUpload.processFile(filePath, fileItemStream, imageName, fileNameExtension); imageName += "." + fileNameExtension; } } } Post currentPost = new Post(); currentPost.setPostID(postService.nextID()); currentPost.setTitle(title); currentPost.setShortTitle(shortTitle); currentPost.setCategory(new Category(Integer.valueOf(sCategoryID), "", false)); currentPost.setContent(content); currentPost.setDatePost(Support.getDatePost()); currentPost.setUser((User) request.getSession().getAttribute(Constants.CURRENT_USER)); currentPost.setLink(link); currentPost.setActive(false); request.setAttribute(Constants.CURRENT_POST, currentPost); request.setAttribute(Constants.LIST_CATEGORY, CategoryDAO.getInstance().getCategories()); if (action != null) { switch (action) { case "up-load": upLoad(request, response, imageName, isUploadSuccess); break; case "add-topic": addTopic(request, response, currentPost); break; } } } catch (IOException | org.apache.tomcat.util.http.fileupload.FileUploadException e) { response.getWriter().println(e.toString()); } }
From source file:org.dspace.rdf.providing.DataProviderServlet.java
/** * Processes requests for both HTTP//from w w w. j a va 2s .c om * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set all incoming encoding to UTF-8 request.setCharacterEncoding("UTF-8"); // we expect either a path containing only the language information // or a path in the form /handle/<prefix>/<suffix>[/language]. String lang = this.detectLanguage(request); String cType = this.detectContentType(request, lang); String pathInfo = request.getPathInfo(); log.debug("lang = " + lang + ", cType = " + cType + " and pathInfo: " + pathInfo); if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) { String dspaceURI = DSpaceServicesFactory.getInstance().getConfigurationService() .getProperty("dspace.url"); this.serveNamedGraph(dspaceURI, lang, cType, response); return; } // remove trailing slash of the path info and split it. String[] path = request.getPathInfo().substring(1).split("/"); // if we have 2 slashes or less, we sent repository information (see above) assert path.length >= 2; String handle = path[0] + "/" + path[1]; log.debug("Handle: " + handle + "."); // As we offer a public sparql endpoint, all information that we stored // in the triplestore is public. It is important to check whether a // DSpaceObject is readable for a anonym user before storing it in the // triplestore. It is important to remove DSpaceObjects from the // triplestore, that gets revoked or become restricted. As this is done // by RDFizer and RDFUtil we do not have to take care for permissions here! Context context = null; DSpaceObject dso = null; try { context = new Context(Context.Mode.READ_ONLY); dso = handleService.resolveToObject(context, handle); } catch (SQLException ex) { log.error("SQLException: " + ex.getMessage(), ex); context.abort(); // probably a problem with the db connection => send Service Unavailable response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } catch (IllegalStateException ex) { log.error("Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex); context.abort(); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (dso == null) { log.info("Cannot resolve handle '" + handle + "' to dso. => 404"); context.abort(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String identifier = null; try { identifier = RDFUtil.generateIdentifier(context, dso); } catch (SQLException ex) { log.error("SQLException: " + ex.getMessage(), ex); context.abort(); // probably a problem with the db connection => send Service Unavailable response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } if (identifier == null) { // cannot generate identifier for dso?! log.error("Cannot generate identifier for UUID " + dso.getID().toString() + "!"); context.abort(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } log.debug("Loading and sending named graph " + identifier + "."); context.abort(); this.serveNamedGraph(identifier, lang, cType, response); }
From source file:org.projectforge.web.servlet.SMSReceiverServlet.java
@Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { log.debug("Start doPost"); // https://projectforge.micromata.de/secure/SMSReceiver?key=<key>&date=20101105171233&sender=01701891142&msg=Hallo... req.setCharacterEncoding("UTF-8"); final String key = req.getParameter("key"); final String expectedKey = configService.getReceiveSmsKey(); if (StringUtils.isBlank(expectedKey) == true) { log.warn(//from ww w.j a v a 2 s . c o m "Servlet call for receiving sms ignored because receiveSmsKey is not given in config.xml file."); response(resp, "NOT YET CONFIGURED"); return; } if (expectedKey.equals(key) == false) { log.warn("Servlet call for receiving sms ignored because receiveSmsKey does not match given key: " + key); response(resp, "DENIED"); return; } final String dateString = req.getParameter("date"); if (StringUtils.isBlank(dateString) == true) { log.warn("Servlet call for receiving sms ignored because parameter 'date' is not given."); response(resp, "Missing parameter 'date'."); return; } final String sender = req.getParameter("sender"); if (StringUtils.isBlank(sender) == true) { log.warn("Servlet call for receiving sms ignored because parameter 'sender' is not given."); response(resp, "Missing parameter 'sender'."); return; } final String msg = req.getParameter("msg"); if (StringUtils.isBlank(msg) == true) { log.warn("Servlet call for receiving sms ignored because parameter 'msg' is not given."); response(resp, "Missing parameter 'msg'."); return; } final Date date = MebDao.parseDate(dateString); if (date == null) { log.warn("Servlet call for receiving sms ignored because couln't parse parameter 'date'."); response(resp, "Unsupported date format."); return; } final MebEntryDO entry = new MebEntryDO(); entry.setDate(date); entry.setSender(sender); entry.setMessage(msg); log.info("Servlet-call: date=[" + date + "], sender=[" + sender + "]"); mebDao.checkAndAddEntry(entry, "SERVLET"); response(resp, "OK"); }
From source file:cn.trymore.core.web.servlet.FileUploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); try {//www.j a v a 2 s .co m DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096); diskFileItemFactory.setRepository(new File(this.tempPath)); String fileIds = ""; ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request); Iterator<FileItem> itor = fileList.iterator(); Iterator<FileItem> itor1 = fileList.iterator(); String file_type = ""; while (itor1.hasNext()) { FileItem item = itor1.next(); if (item.isFormField() && "file_type".equals(item.getFieldName())) { file_type = item.getString(); } } FileItem fileItem; while (itor.hasNext()) { fileItem = itor.next(); if (fileItem.getContentType() == null) { continue; } // obtains the file path and name String filePath = fileItem.getName(); String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); // generates new file name with the current time stamp. String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName); // ensure the directory existed before creating the file. File dir = new File( this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1)); if (!dir.exists()) { dir.mkdirs(); } // stream writes to the destination file fileItem.write(new File(this.uploadPath + "/" + newFileName)); ModelFileAttach fileAttach = null; if (request.getParameter("noattach") == null) { // storages the file into database. fileAttach = new ModelFileAttach(); fileAttach.setFileName(fileName); fileAttach.setFilePath(newFileName); fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize())); fileAttach.setNote(this.getStrFileSize(fileItem.getSize())); fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1)); fileAttach.setCreatetime(new Date()); fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL); fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat); ModelAppUser user = ContextUtil.getCurrentUser(); if (user != null) { fileAttach.setCreatorId(Long.valueOf(user.getId())); fileAttach.setCreator(user.getFullName()); } else { fileAttach.setCreator("Unknow"); } this.serviceFileAttach.save(fileAttach); } //add by Tang ??fileIds????? if (fileAttach != null) { fileIds = (String) request.getSession().getAttribute("fileIds"); if (fileIds == null) { fileIds = fileAttach.getId(); } else { fileIds = fileIds + "," + fileAttach.getId(); } } response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.println( "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"") + ", \"url\":\"" + newFileName + "\"}}"); } request.getSession().setAttribute("fileIds", fileIds); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\""); } }
From source file:com.iwebirth.controller.AdminController.java
/** * */*from w w w .j a va2s . com*/ */ @RequestMapping(value = { "/update/{obj_id}" }, method = RequestMethod.POST) public @ResponseBody AjaxResult updateRecord(@PathVariable int obj_id, HttpServletRequest request, HttpSession session) throws UnsupportedEncodingException { LoginStatus status = (LoginStatus) session.getAttribute("login_status"); if (status == null || !status.getAlive()) return null; request.setCharacterEncoding("utf-8"); AjaxResult ajaxResult = new AjaxResult(false); try { switch (obj_id) { //User case user_id: User user = new User(); user.setId(Integer.parseInt(request.getParameter("id"))); user.setUsername(request.getParameter("username")); user.setPassword(request.getParameter("password")); user.setUserLevel(request.getParameter("userLevel")); user.setDepartmentId(Integer.parseInt(request.getParameter("departmentId"))); user.setIsValid(Boolean.parseBoolean(request.getParameter("isValid"))); ajaxResult.setResult(CRUDEvent.getNameByValue(adminService.updateObject(user))); break; case department_id: Department depart = new Department(); depart.setId(Integer.parseInt(request.getParameter("id"))); depart.setName(request.getParameter("name")); depart.setLocation(request.getParameter("location")); depart.setFunction(request.getParameter("function")); depart.setLatitude(request.getParameter("latitude")); depart.setLongitude(request.getParameter("longitude")); ajaxResult.setResult(CRUDEvent.getNameByValue(adminService.updateObject(depart))); break; case vehicle_id: Vehicle vehicle = new Vehicle(); vehicle.setId(Integer.parseInt(request.getParameter("id"))); vehicle.setTerminalId(request.getParameter("terminalId")); vehicle.setType(request.getParameter("type")); vehicle.setTerminalLicense(request.getParameter("terminalLicense")); vehicle.setCurrentStatus(request.getParameter("currentStatus")); vehicle.setBelongId(Integer.parseInt(request.getParameter("belongId"))); vehicle.setOriginId(Integer.parseInt(request.getParameter("originId"))); vehicle.setRecentRentId(Integer.parseInt(request.getParameter("recentRentId"))); vehicle.setRecentSellId(Integer.parseInt(request.getParameter("recentSellId"))); ajaxResult.setResult(CRUDEvent.getNameByValue(adminService.updateObject(vehicle))); break; } } catch (Exception e) { e.printStackTrace(); } return ajaxResult; }
From source file:com.netcracker.tss.web.servlet.customer.CustomerMMGServiceServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w . ja v a 2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); try { if (request.getParameter("addFrom") != null) { addAddressFrom(request); response.sendRedirect("/customer/orderpage"); } else if (request.getParameter("addTo") != null) { addAddressTo(request); response.sendRedirect("/customer/orderpage"); } else if (request.getParameter("deleteTo") != null || request.getParameter("deleteFrom") != null) { deleteAddress(request); response.sendRedirect("/customer/orderpage"); } else { Date bookingTime = new Date(); Date orderTime = DateParser.parseDate(request); if (orderTime.before(bookingTime)) { request.setAttribute("errorMessage", "It is impossible to order taxi at the past! Please input the correct order time."); redirectToTaxiOrder(request, response); // req.getRequestDispatcher("/customer/orderpage").forward(req, resp); // resp.sendRedirect("/customer/orderpage?err=It is impossible to order taxi at the past! Please input the correct order time."); } else { User user = findCurrentUser(); MeetMyGuestBeanLocal myGuestBeanLocal = getMeetMyGuestBean(request); TaxiOrderBeanLocal taxiOrderBeanLocal = getTaxiOrderBean(request); PriceBeanLocal priceBean = getPriceBean(request); float distance = 0; double price = 0; Route route = new Route(findCurrentUser().getUsername() + " Route"); route.setDistance(distance); Address addFrom = toAddress(request.getParameter("fromAddr"), request); Address addTo = toAddress(request.getParameter("toAddr"), request); TaxiOrder taxiOrder = new TaxiOrder(AdditionalParameters.taxiOrderAddParameters(request)); MapBeanLocal mapBean = getMapBean(request); distance = mapBean.calculateDistance(request.getParameter("fromAddr"), request.getParameter("toAddr")); price = priceBean.calculatePrice(distance, DateParser.parseDate(request), taxiOrder, UserUtils.findCurrentUser()); taxiOrder.setBookingTime(bookingTime); taxiOrder.setOrderTime(orderTime); taxiOrder.setPrice(price); String guestName = request.getParameter("guestName"); myGuestBeanLocal.addMeetMyGuestService(user, route, addFrom, addTo, taxiOrder, guestName); int latestTOId = taxiOrderBeanLocal.getTaxiOrderHistory(1, 1, user).get(0).getId(); request.setAttribute("taxiOrderId", latestTOId); request.setAttribute("pageContent", "content/confirmation.jsp"); request.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(request, response); } } } catch (Exception e) { Logger.getLogger(CustomerSoberServiceServlet.class.getName()).log(Level.SEVERE, e.getMessage(), e); request.setAttribute("errorMessage", "Sorry, we can not make this order! Please, check all input parameters ad try again."); redirectToTaxiOrder(request, response); // response.sendRedirect( // "/customer/mmgServicePage?err=Sorry, we can not make this order! Please, check all input parameters ad try again."); } }
From source file:flex.webtier.server.j2ee.MxmlServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try {/*ww w . j a va 2s. com*/ // encoding must be set before any access to request parameters request.setCharacterEncoding("UTF-8"); MxmlContext context = new MxmlContext(); context.setRequest(request); context.setResponse(response); context.setServletContext(getServletContext()); context.setPageTitle(request.getServletPath()); setupMxmlContextKeys(getServletContext(), context, request); context.setDetectionSettings(DetectionSettingsFactory.getInstance(request.getContextPath())); context.setHistorySettings(HistorySettingsFactory.getInstance(request.getContextPath())); if (!ServiceFactory.getLicenseService().isMxmlCompileEnabled()) { response.sendError(481, "The current license does not support this feature."); ServiceFactory.getLogger().logError( "The current license does not support this feature. request=" + request.getServletPath()); return; } if (isObjectRequest(request)) { if (request.getParameter("w") != null) { context.setWidth(request.getParameter("w")); } else { context.setWidth("100%"); } if (request.getParameter("h") != null) { context.setHeight(request.getParameter("h")); } else { context.setHeight("100%"); } objectFilterChain.invoke(context); } else { PathResolver.setThreadLocalPathResolver(new ServletPathResolver(getServletContext())); flex2.compiler.common.PathResolver resolver = new flex2.compiler.common.PathResolver(); resolver.addSinglePathResolver( new flex.webtier.server.j2ee.ServletPathResolver(getServletContext())); resolver.addSinglePathResolver(LocalFilePathResolver.getSingleton()); resolver.addSinglePathResolver(URLPathResolver.getSingleton()); ThreadLocalToolkit.setPathResolver(resolver); // set up for localizing messages LocalizationManager localizationManager = new LocalizationManager(); localizationManager.addLocalizer(new XLRLocalizer()); localizationManager.addLocalizer(new ResourceBundleLocalizer()); ThreadLocalToolkit.setLocalizationManager(localizationManager); setupCompileEventLogger(context, request); setupSourceCodeLoader(context); filterChain.invoke(context); } } catch (FileNotFoundException fnfe) { // return an error page HttpCache.setCacheHeaders(false, 0, -1, response); response.sendError(HttpServletResponse.SC_NOT_FOUND, fnfe.getMessage()); if (logCompilerErrors) { ServiceFactory.getLogger().logError(fnfe.getMessage(), fnfe); } } catch (Throwable t) { // return an error page ServiceFactory.getLogger().logError("Unknown error " + request.getServletPath() + ": " + t.getMessage(), t); throw new ServletException(t); } finally { ServletUtils.clearThreadLocals(); } }
From source file:com.kirayim.homesec.service.impl.ImageManagerImpl.java
@Override public Image handleFileUpload(long cameraId, HttpServletRequest request) { String extension = null;// w ww .j av a 2 s .c o m Date uploadTime = new Date(); String encoding = request.getCharacterEncoding(); if (encoding == null) { try { request.setCharacterEncoding(encoding = "UTF-8"); } catch (UnsupportedEncodingException ex) { logger.warn("Bad encoding", ex); } } User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Camera camera = cameraManager.get(cameraId); if (camera == null) { throw new NotAllowedException("Imvalid camera ID"); } if (!camera.getOwner().equals(user)) { throw new NotAllowedException("Camera doesn't belong to current user"); } /* ------------------------------------------------- * Calculate output file name * ------------------------------------------------- */ String name = String.format("homesec_image_%1$08d_%2$TY%2$Tm%2$Td_%2$TH%2$TM%2$TS%2$TL", camera.getCameraId(), uploadTime); /* ------------------------------------------------- * Get uploaded file and write to destination * ------------------------------------------------- */ try { if (request.getParts().size() > 1) { throw new NotAllowedException("Only one image upload per transaction"); } for (Part part : request.getParts()) { if (!uploadDir.exists()) { uploadDir.mkdirs(); } String contentType = part.getContentType(); if (contentType != null) { try { MimeTypes allTypes = MimeTypes.getDefaultMimeTypes(); MimeType mimeType = allTypes.forName(contentType); extension = mimeType.getExtension(); name += extension; } catch (MimeTypeException mimeTypeException) { logger.warn("Mime? ", mimeTypeException); } } File outputFile = new File(uploadDir, name); OutputStream out = new FileOutputStream(outputFile); InputStream in = part.getInputStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } catch (IOException | ServletException e) { throw new BadRequestException(e); } /* ------------------------------------------------- * If extension is unknown, re-read file to try * and get extension * ------------------------------------------------- */ if (extension == null) { // TODO: } /* ------------------------------------------------- * Save image record in DB * ------------------------------------------------- */ Image image = new Image(camera, name, uploadTime); dao.save(image); return image; }
From source file:com.ikon.servlet.admin.CronTabServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);//ww w .j a v a 2 s. c o m try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); CronTab ct = new CronTab(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("ct_id")) { ct.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("ct_name")) { ct.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_mail")) { ct.setMail(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_expression")) { ct.setExpression(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_active")) { ct.setActive(true); } } else { is = item.getInputStream(); ct.setFileName(FilenameUtils.getName(item.getName())); ct.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); ct.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); is.close(); } } if (action.equals("create")) { CronTabDAO.create(ct); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_CREATE", null, null, ct.toString()); list(request, response); } else if (action.equals("edit")) { CronTabDAO.update(ct); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_EDIT", Long.toString(ct.getId()), null, ct.toString()); list(request, response); } else if (action.equals("delete")) { CronTabDAO.delete(ct.getId()); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_DELETE", Long.toString(ct.getId()), null, null); list(request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:controller.insertProduct.java
private void insertProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String productType = null;/* www . ja va 2 s . c om*/ String resolution = null; String hdmi = null; String usb = null; String model = null; String size = null; String warranty = null; String productName = null; int price = 0; String description = null; Integer quantity = null; String produceID = null; String image = null; String uploadDirectory = "/Product/Images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_THRESHOLD); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); File uploadDir; File storeFile; try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadDirectory + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); image = produceID + "/" + fileName; System.out.println(storeFile.getPath()); } else { switch (item.getFieldName()) { case "productName": productName = item.getString("UTF-8"); break; case "produceID": { produceID = item.getString("UTF-8"); uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID); if (!uploadDir.exists()) { uploadDir.mkdir(); } uploadDirectory = uploadPath + uploadDirectory + "/" + produceID; break; } case "price": price = (Integer.parseInt(item.getString("UTF-8"))); break; case "quantity": quantity = (Integer.parseInt(item.getString("UTF-8"))); break; case "productType": productType = item.getString("UTF-8"); break; case "resolution": resolution = item.getString("UTF-8"); break; case "hdmi": hdmi = item.getString("UTF-8"); break; case "usb": usb = item.getString("UTF-8"); break; case "Model": model = item.getString("UTF-8"); break; case "size": size = item.getString("UTF-8"); break; case "warranty": warranty = item.getString("UTF-8"); break; case "description": { description = item.getString("UTF-8"); System.out.println(description); break; } } } } } } catch (Exception ex) { System.out.println(ex); } @SuppressWarnings("null") ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty); Products product = new Products(productName, price, description, quantity, image, prinfo, produceID); if (ProductsDAO.insertProduct(product)) { out.print( "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } else { out.print( "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } }