List of usage examples for javax.servlet.http HttpServletRequest getServletContext
public ServletContext getServletContext();
From source file:com.glaf.core.web.servlet.SpringDispatcherServlet.java
@Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("RequestURI:" + request.getRequestURI()); try {// w w w. j av a 2 s . c o m String systemName = RequestUtils.getCurrentSystem(request); if (systemName != null && !StringUtils.equals("GLAF", systemName)) { Environment.setCurrentSystemName(systemName); } String actorId = RequestUtils.getActorId(request); if (actorId != null) { // logger.debug("actorId:" + actorId); Authentication.setAuthenticatedActorId(actorId); } LoginContext user = RequestUtils.getLoginContext(request); if (user != null) { Authentication.setLoginContext(user); com.glaf.core.security.Authentication.setAuthenticatedActorId(user.getActorId()); } /** * ?????? */ if ((user == null) || (!user.isSystemAdministrator())) { String uri = request.getRequestURI(); logger.debug("request uri:" + uri); } } catch (Exception ex) { ex.printStackTrace(); } ThreadContextHolder.setHttpRequest(request); ThreadContextHolder.setHttpResponse(response); ThreadContextHolder.setServletContext(request.getServletContext()); try { super.doService(request, response); } finally { Environment.setCurrentSystemName(null); Environment.removeCurrentSystemName(); Environment.clear(); Authentication.clear(); ThreadContextHolder.clear(); ConnectionThreadHolder.closeAndClear(); } }
From source file:password.pwm.http.filter.RequestInitializationFilter.java
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) servletRequest; final HttpServletResponse resp = (HttpServletResponse) servletResponse; final PwmApplicationMode mode = PwmApplicationMode.determineMode(req); final PwmURL pwmURL = new PwmURL(req); PwmApplication testPwmApplicationLoad = null; try {//from w ww. j ava 2 s . co m testPwmApplicationLoad = ContextManager.getPwmApplication(req); } catch (PwmException e) { } if (testPwmApplicationLoad == null && pwmURL.isResourceURL()) { filterChain.doFilter(req, resp); } else if (pwmURL.isStandaloneWebService() || pwmURL.isJerseyWebService()) { filterChain.doFilter(req, resp); } else { if (mode == PwmApplicationMode.ERROR) { try { final ContextManager contextManager = ContextManager.getContextManager(req.getServletContext()); if (contextManager != null) { final ErrorInformation startupError = contextManager.getStartupErrorInformation(); servletRequest.setAttribute(PwmRequestAttribute.PwmErrorInfo.toString(), startupError); } } catch (Exception e) { if (pwmURL.isResourceURL()) { filterChain.doFilter(servletRequest, servletResponse); return; } LOGGER.error("error while trying to detect application status: " + e.getMessage()); } LOGGER.error("unable to satisfy incoming request, application is not available"); resp.setStatus(500); final String url = JspUrl.APP_UNAVAILABLE.getPath(); servletRequest.getServletContext().getRequestDispatcher(url).forward(servletRequest, servletResponse); } else { initializeServletRequest(req, resp, filterChain); } } }
From source file:be.fedict.eid.idp.webapp.ProtocolEntryServlet.java
private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { LOG.debug("handle request"); LOG.debug("request URI: " + request.getRequestURI()); LOG.debug("request method: " + request.getMethod()); LOG.debug("request path info: " + request.getPathInfo()); LOG.debug("request context path: " + request.getContextPath()); LOG.debug("request query string: " + request.getQueryString()); LOG.debug("request path translated: " + request.getPathTranslated()); String userAgent = request.getHeader("User-Agent"); if (invalidUserAgent(userAgent)) { LOG.warn("unsupported user agent: " + userAgent); response.sendRedirect(request.getContextPath() + this.unsupportedBrowserPageInitParam); return;// w ww.j av a 2s. com } String protocolServiceContextPath = request.getPathInfo(); setProtocolServiceContextPath(protocolServiceContextPath, request); ServletContext servletContext = request.getServletContext(); Map<String, IdentityProviderProtocolService> protocolServices = getProtocolServices(servletContext); IdentityProviderProtocolService protocolService = protocolServices.get(protocolServiceContextPath); if (null == protocolService) { LOG.warn("unsupported protocol: " + protocolServiceContextPath); response.sendRedirect(request.getContextPath() + this.unknownProtocolPageInitParam); return; } /* Explicitamente deshabilitamos los protocolos relacionados con Identification debido a que la tarjeta del Banco Central no contiene informacion de identidad. El TLV parsing del archivo de identidad de Belgica esta estrictamente ligado a la disposicion fisica de la informacion en esa tarjeta y no se tiene ninguna analogia reutilizable en la tarjeta del Banco Central por el momento.*/ if (request.getPathInfo().equals("/openid/ident") || request.getPathInfo().equals("/openid/auth-ident") || request.getPathInfo().equals("/saml2/post/ident") || request.getPathInfo().equals("/saml2/post/auth-ident") || request.getPathInfo().equals("/saml2/redirect/ident") || request.getPathInfo().equals("/saml2/redirect/auth-ident") || request.getPathInfo().equals("/saml2/artifact/ident") || request.getPathInfo().equals("/saml2/artifact/auth-ident") || request.getPathInfo().equals("/saml2/ws-federation/ident") || request.getPathInfo().equals("/saml2/ws-federation/auth-ident")) { LOG.warn("unsupported protocol: " + protocolServiceContextPath); response.sendRedirect(request.getContextPath() + this.unknownProtocolPageInitParam); return; } try { IncomingRequest incomingRequest = protocolService.handleIncomingRequest(request, response); if (null == incomingRequest) { LOG.debug("the protocol service handler " + "defined its own response flow"); return; } // optionally authenticate RP LOG.debug("SP Domain: " + incomingRequest.getSpDomain()); request.getSession().setAttribute(Constants.RP_DOMAIN_SESSION_ATTRIBUTE, incomingRequest.getSpDomain()); RPEntity rp = this.rpService.find(incomingRequest.getSpDomain()); if (null != rp) { if (!isValid(rp, incomingRequest, request, response)) { return; } } // set preferred language if possible LOG.debug("Languages: " + incomingRequest.getLanguages()); if (null != incomingRequest.getLanguages() && !incomingRequest.getLanguages().isEmpty()) { request.getSession().setAttribute(SP.LANGUAGE_LIST_SESSION_ATTRIBUTE, incomingRequest.getLanguages()); } // check required attributes if set if (null != incomingRequest.getRequiredAttributes() && !incomingRequest.getRequiredAttributes().isEmpty()) { for (String attributeProtocolUri : incomingRequest.getRequiredAttributes()) { // lookup attribute AttributeEntity attribute = this.attributeService.findAttribute(protocolService.getId(), attributeProtocolUri); if (null == attribute) { redirectToErrorPage("Required attribute \"" + attributeProtocolUri + "\" not available.", request, response); return; } // check RP's config if necessary if (null != rp) { boolean found = false; for (RPAttributeEntity rpAttribute : rp.getAttributes()) { if (rpAttribute.getAttribute().equals(attribute)) { found = true; break; } } if (!found) { redirectToErrorPage( "Required attribute \"" + attributeProtocolUri + "\" not available.", request, response); return; } } } } request.getSession().setAttribute(Constants.IDP_FLOW_SESSION_ATTRIBUTE, incomingRequest.getIdpFlow()); switch (incomingRequest.getIdpFlow()) { case AUTHENTICATION: case AUTHENTICATION_WITH_IDENTIFICATION: response.sendRedirect(request.getContextPath() + this.authenticationPageInitParam); break; case IDENTIFICATION: response.sendRedirect(request.getContextPath() + this.identificationPageInitParam); break; default: throw new RuntimeException("cannot handle " + "IdP flow: " + incomingRequest.getIdpFlow()); } // accounting this.accountingService.addRequest(incomingRequest.getSpDomain()); } catch (Exception e) { LOG.error("protocol error: " + e.getMessage(), e); redirectToErrorPage(e.getMessage(), request, response); } }
From source file:servlets.Photo.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String action = request.getParameter("action"); if (action != null) { switch (action) { case "upload": boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); }// ww w. j a v a2 s . c o m Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (!item.isFormField() && item.getSize() > 0) { try { System.out.println("FieldName=" + item.getFieldName()); System.out.println("FileName=" + item.getName()); System.out.println("ContentType=" + item.getContentType()); System.out.println("Size in bytes=" + item.getSize()); File file = new File(request.getServletContext().getRealPath("/") + "Media" + File.separator + item.getName()); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); item.write(file); } catch (Exception ex) { ex.printStackTrace(); } } } request.getRequestDispatcher("upload.jsp").forward(request, response); } else { request.getRequestDispatcher("upload.jsp").forward(request, response); } break; } } else { request.getRequestDispatcher("upload.jsp").forward(request, response); } }
From source file:servlets.InsertToken.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a2 s .c o m * * @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 { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String amount = request.getParameter("amount"); String email = user.getEmail(); String action = request.getParameter("action"); if (amount.equals("")) { ArrayList<PageMessage> errors = new ArrayList(); PageMessage e1 = new PageMessage(); e1.setText(" obrigatrio a insero de um valor para a transferncia."); e1.setType("danger"); errors.add(e1); session.setAttribute("messages", errors); response.sendRedirect("transaction.jsp"); } Calendar cal = Calendar.getInstance(); int mi = cal.get(Calendar.MILLISECOND); int code = (int) Math.abs((Math.random() * 1000) * mi); Calendar cal2 = Calendar.getInstance(); int h = cal2.get(Calendar.HOUR_OF_DAY); int d = cal2.get(Calendar.DAY_OF_MONTH); int token = Math.abs((code * code * h) / (d)); try { Email.sendToken(email, Integer.toString(token)); } catch (EmailException ex) { internalError(session, response); } request.setAttribute("code", code); request.setAttribute("amount", amount); request.setAttribute("action", action); RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/insertToken.jsp"); rd.forward(request, response); }
From source file:io.hops.hopsworks.api.user.AuthService.java
@POST @Path("ldapLogin") @Produces(MediaType.APPLICATION_JSON)/* w w w.j av a 2 s .c o m*/ public Response ldapLogin(@FormParam("username") String username, @FormParam("password") String password, @FormParam("chosenEmail") String chosenEmail, @FormParam("consent") boolean consent, @Context HttpServletRequest req) throws LoginException, UserException { RESTApiJsonResponse json = new RESTApiJsonResponse(); if (username == null || username.isEmpty()) { throw new IllegalArgumentException("Username can not be empty."); } if (password == null || password.isEmpty()) { throw new IllegalArgumentException("Password can not be empty."); } LdapUserState ldapUserState = ldapUserController.login(username, password, consent, chosenEmail); if (!ldapUserState.isSaved()) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(ldapUserState.getUserDTO()).build(); } LdapUser ladpUser = ldapUserState.getLdapUser(); if (ladpUser == null || ladpUser.getUid() == null) { throw new LoginException("Failed to get ldap user from table."); } Users user = ladpUser.getUid(); // Do pre cauth realm check String passwordWithSalt = authController.preLdapLoginCheck(user, ladpUser.getAuthKey()); if (req.getRemoteUser() != null && !req.getRemoteUser().equals(user.getEmail())) { logoutAndInvalidateSession(req); } //only login if not already logged... if (req.getRemoteUser() == null) { login(user, user.getEmail(), passwordWithSalt, req); } else { req.getServletContext().log("Skip logged because already logged in: " + username); } //read the user data from db and return to caller json.setSessionID(req.getSession().getId()); json.setData(user.getEmail()); return Response.status(Response.Status.OK).entity(json).build(); }
From source file:cdc.util.Upload.java
public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { int cont = 0; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = null; try {/*from w w w.j av a 2s .c o m*/ fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } String optionalFileName = ""; FileItem fileItem = null; Iterator it = fileItemsList.iterator(); do { //cont++; FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.isFormField()) { if (fileItemTemp.getFieldName().equals("file")) { optionalFileName = fileItemTemp.getString(); } } else { fileItem = fileItemTemp; } if (cont != (fileItemsList.size())) { if (fileItem != null) { String fileName = fileItem.getName(); if (fileItem.getSize() > 0) { if (optionalFileName.trim().equals("")) { fileName = FilenameUtils.getName(fileName); } else { fileName = optionalFileName; } String dirName = request.getServletContext().getRealPath(pasta); File saveTo = new File(dirName + fileName); //System.out.println("caminho: " + saveTo.toString() ); try { fileItem.write(saveTo); } catch (Exception e) { } } } } cont++; } while (it.hasNext()); return true; } else { return false; } }
From source file:com.ccsna.safetynet.NewsServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// www . j av a 2 s .co m * * @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 { response.setContentType("text/html;charset=UTF-8"); try { PrintWriter out = response.getWriter(); String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "", endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null; Date sDate = null, eDate = null; Time eTime = null, sTime = null; int action = 0, newsId = 0; boolean dataValid = true; News news = null; String fullPath = null; Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession()); if (loggedInMember != null) { String createdBy = String.valueOf(loggedInMember.getMemberId()); boolean isMultipart = ServletFileUpload.isMultipartContent(request); log.info("isMultipart :" + isMultipart); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String appPath = request.getServletContext().getRealPath(""); //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot"; //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/"; try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { //log.info("item is form field"); String fileName = item.getName(); //log.info("the name of the item is :" + fileName); String contentType = item.getContentType(); //log.info("the content type is :" + contentType); if (item.getContentType().equalsIgnoreCase(JPEG) || item.getContentType().equalsIgnoreCase(JPG) || item.getContentType().equalsIgnoreCase(PDF)) { String root = appPath; log.info("pdf content recognised"); log.info("root path is :" + appPath); //String smallLoc = "/uploads/small"; String largeLoc = "/uploads/large"; log.info("largeLoc:" + largeLoc); //File pathSmall = new File(root + smallLoc); File pathLarge = new File(root + largeLoc); //log.info("small image path :" + pathSmall); log.info("large image path :" + pathLarge); if (!pathLarge.exists()) { // boolean status = pathSmall.mkdirs(); pathLarge.mkdirs(); } if (item.getContentType().equalsIgnoreCase(PDF)) { log.info("loading pdf file"); fileType = Menu.PDF; fileName = createdBy + "_" + System.currentTimeMillis() + "." + PDF_EXTENSION; //File uploadedFileSmall = new File(pathSmall + "/" + fileName); File uploadedFileLarge = new File(pathLarge + "/" + fileName); Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge); } else { fileType = Menu.IMAGE; fileName = createdBy + "_" + System.currentTimeMillis() + "." + JPEG_EXTENSION; log.info("filename is : " + fileName); // File uploadedFileSmall = new File(pathSmall + "/" + fileName); File uploadedFileLarge = new File(pathLarge + "/" + fileName); //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall); Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge); } //smallUrl = smallLoc + "/" + fileName + ""; largeUrl = largeLoc + "/" + fileName + ""; log.info("largeUrl image url is :" + largeUrl); fullPath = request.getContextPath() + "/" + largeUrl; } } else { if (item.getFieldName().equalsIgnoreCase("newsTitle")) { title = item.getString(); log.info("title is :" + title); } if (item.getFieldName().equalsIgnoreCase("type")) { newsType = item.getString(); log.info("newsType is :" + newsType); } if (item.getFieldName().equalsIgnoreCase("content")) { content = item.getString(); log.info("content is :" + content); } if (item.getFieldName().equalsIgnoreCase("start_Date")) { startDate = item.getString(); if (startDate != null && !startDate.isEmpty()) { sDate = Menu .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd")); } log.info("startDate is :" + startDate); } if (item.getFieldName().equalsIgnoreCase("end_Date")) { endDate = item.getString(); if (endDate != null && !endDate.isEmpty()) { eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd")); } log.info("endDate is :" + endDate); } if (item.getFieldName().equalsIgnoreCase("action")) { action = Integer.parseInt(item.getString()); log.info("the action is :" + action); } if (item.getFieldName().equalsIgnoreCase("newsId")) { newsId = Integer.parseInt(item.getString()); log.info("the newsid is :" + newsId); } if (item.getFieldName().equalsIgnoreCase("status")) { st = item.getString(); log.info("the status is :" + st); } if (item.getFieldName().equalsIgnoreCase("end_Time")) { endTime = item.getString(); if (endTime != null && !endTime.isEmpty()) { eTime = Menu.convertStringToSqlTime(endTime); } log.info("eTime is :" + eTime); } if (item.getFieldName().equalsIgnoreCase("start_Time")) { startTime = item.getString(); if (startTime != null && !startTime.isEmpty()) { sTime = Menu.convertStringToSqlTime(startTime); } log.info("sTime is :" + sTime); } } } } catch (FileUploadException e) { e.printStackTrace(); } } switch (Validation.Actions.values()[action]) { case CREATE: log.info("creating new serlvet ................"); { news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy, Menu.ACTIVE, largeUrl, fileType, fullPath); } if (news != null) { log.info("news successfully created..."); message += "News item has been successfully added"; Validation.setAttributes(request, Validation.SUCCESS, message); response.sendRedirect(request.getContextPath() + "/admin/management.jsp"); } else { log.info("news creating failed..."); message += "Unable to add news item"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + "/admin/management.jsp"); } break; case UPDATE: log.info("updating news ..."); if (title != null && !title.isEmpty()) { news = new NewsModel().findByParameter("title", title); } if (news != null && (news.getNewsId() == newsId)) { log.info("news is :" + news.getNewsId()); dataValid = true; } else { dataValid = false; } if (news == null) { dataValid = true; } log.info("dataValid is :" + dataValid); if (dataValid) { boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate, eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime); if (newsUpdated) { message += "News/Alert has been successfully updated"; Validation.setAttributes(request, Validation.SUCCESS, message); response.sendRedirect(request.getContextPath() + "/admin/management.jsp"); } else { message += "Unable to update news item"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + "/admin/newsEdit.jsp?id=" + newsId); } } else { message += "News with same title already exist, Enter a different title"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + "/admin/newsEdit.jsp?id=" + newsId); } break; } } else { message += "Session expired, Kindly login with username and password"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + "/index.jsp"); } } catch (Exception e) { } }
From source file:org.everit.authentication.cas.CasAuthentication.java
/** * Performs a CAS service ticket validation. The following tasks are done if the service ticket is * valid:/*from w ww .j a va2 s .com*/ * <ul> * <li>The authenticated username/principal sent by the CAS server is mapped to a Resource ID. * </li> * <li>The mapped Resource ID is added to the {@link HttpSession} with the name provided by the * {@link AuthenticationSessionAttributeNames#authenticatedResourceId()} method. This Resource ID * will be picked up by the {@link Filter} provided by the * <a href="https://github.com/everit-org/authentication-http-session">authentication-http-session * </a> component and that filter will execute the authenticated process in the name of the * authenticated user.</li> * <li>A {@link CasHttpSessionActivationListener} is also registered to the session to handle * session passivation and activation events (for e.g. in case of persistent sessions).</li> * <li>The {@link HttpSession} is registered to the {@link CasHttpSessionRegistry} stored in the * {@link ServletContext} to be able to handle CAS logout requests (invalidate the proper session * belonging to the service ticket).</li> * <li>Redirects the response to the service URL.</li> * </ul> */ private void performServiceTicketValidation(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final String serviceTicket) throws IOException { String serviceUrl = createServiceUrl(httpServletRequest); String locale = getRequestParameter(httpServletRequest, LOCALE); try { String principal = validateServiceTicket(serviceUrl, serviceTicket, locale); Long authenticatedResourceId = resourceIdResolver.getResourceId(principal) .orElseThrow(() -> new IllegalStateException("The principal [" + principal + "] of the valid service ticket cannot be mapped to a Resource ID." + " The session will not be assigned to any Resource ID.")); HttpSession httpSession = httpServletRequest.getSession(); httpSession.setAttribute(authenticationSessionAttributeNames.authenticatedResourceId(), authenticatedResourceId); CasHttpSessionActivationListener.registerInstance(servicePid, httpSession); ServletContext servletContext = httpServletRequest.getServletContext(); CasHttpSessionRegistry casHttpSessionRegistry = CasHttpSessionRegistry.getInstance(servicePid, servletContext); casHttpSessionRegistry.put(serviceTicket, httpSession); httpServletResponse.sendRedirect(serviceUrl); } catch (IllegalStateException | TicketValidationException e) { handleError(httpServletResponse, e.getMessage(), e); } }
From source file:src.addImage.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from ww w . jav a2s . c om User user = (User) req.getSession().getAttribute("user"); if (user == null) { resp.sendRedirect("login.jsp"); return; } if (user.getUserType().getType().equals("Admin") || user.getUserType().getType().equals("Root")) { } else { resp.sendRedirect("login.jsp"); return; } String pid = ""; String pcode = ""; String imgpath = ""; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Object> items = upload.parseRequest(req); for (Object element : items) { FileItem fileitem = (FileItem) element; if (fileitem.isFormField()) { if (fileitem.getFieldName().equals("pid")) { //getFieldName() - FIELD eke variable name(HTML) eka pid = fileitem.getString(); // getString() - FIELD eke value eka. } if (fileitem.getFieldName().equals("pcode")) { pcode = fileitem.getString(); } } else { imgpath = "partials/assets/img/gallery/" + System.currentTimeMillis() + fileitem.getName(); // File savedFile = new File("http://localhost:8080/MobiShop/" + imgpath); File savedFile = new File(req.getServletContext().getRealPath("/") + imgpath); // System.out.println(req.getServletContext().getRealPath("/")); fileitem.write(savedFile); } } Session con = FactoryManager.getSessionFactory().openSession(); Transaction t = con.beginTransaction(); Products p; if (!pid.equals("") && !imgpath.equals("")) { p = (Products) con.load(Products.class, Integer.parseInt(pid)); } else if (!pcode.equals("") && !imgpath.equals("")) { Criteria cri = con.createCriteria(Products.class); cri.add(Restrictions.eq("prodCode", pcode)); p = (Products) cri.list().get(0); } else { String msg = "Something wrong with your inputs!"; int type = 1; resp.sendRedirect("admin_edit_items.jsp?msg=" + msg + "&msgtype=" + type); return; } p.setImgUrl(imgpath); con.save(p); t.commit(); String msg = "Success!"; int type = 0; resp.sendRedirect("admin_edit_items.jsp?msg=" + msg + "&msgtype=" + type); } catch (Exception e) { // resp.getWriter().write(e.toString()); e.printStackTrace(); resp.sendError(500); } }