List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:edu.lternet.pasta.portal.ScopeBrowseServlet.java
/** * The doPost method of the servlet. <br> * /*ww w .j ava 2s.c o m*/ * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); String uid = (String) httpSession.getAttribute("uid"); if (uid == null || uid.isEmpty()) uid = "public"; String text = null; String html = null; Integer count = 0; try { DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid); text = dpmClient.listDataPackageScopes(); StrTokenizer tokens = new StrTokenizer(text); html = "<ol>\n"; ArrayList<String> arrayList = new ArrayList<String>(); // Add scope values to a sorted set while (tokens.hasNext()) { String token = tokens.nextToken(); arrayList.add(token); count++; } // Output sorted set of scope values for (String scope : arrayList) { html += "<li><a class=\"searchsubcat\" href=\"./identifierbrowse?scope=" + scope + "\">" + scope + "</a></li>\n"; } html += "</ol>\n"; } catch (Exception e) { handleDataPortalError(logger, e); } request.setAttribute("browsemessage", browseMessage); request.setAttribute("html", html); request.setAttribute("count", count.toString()); RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward); requestDispatcher.forward(request, response); }
From source file:com.alfaariss.oa.sso.web.profile.logout.LogoutProfile.java
private void showLogoutJSP(HttpServletRequest servletRequest, HttpServletResponse servletResponse, SessionState state, String sessionID, List<TGTEventError> warnings) throws OAException { try {/*from w w w . j av a2 s . c o m*/ if (sessionID != null) servletRequest.setAttribute(ISession.ID_NAME, sessionID); if (state != null) servletRequest.setAttribute(JSP_LOGOUT_STATE, state); if (warnings != null) { servletRequest.setAttribute(DetailedUserException.DETAILS_NAME, warnings); } //Show user info //Set server info as attribute servletRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer()); //Forward to page RequestDispatcher oDispatcher = servletRequest.getRequestDispatcher(_sJSPUserLogout); if (oDispatcher != null) oDispatcher.forward(servletRequest, servletResponse); else { _logger.fatal("Forward request not supported"); throw new OAException(SystemErrors.ERROR_INTERNAL); } } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during jsp forward to logout page", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:edu.um.umflix.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, String> mapValues = new HashMap<String, String>(); List<Clip> clips = new ArrayList<Clip>(); List<Byte[]> listData = new ArrayList<Byte[]>(); int i = 0;/*from www . j a v a2 s.c o m*/ try { List<FileItem> items = getFileItems(request); for (FileItem item : items) { if (item.isFormField()) { // Process normal fields here. mapValues.put(item.getFieldName(), item.getString()); // w.print("Field name: " + item.getFieldName()); // w.print("Field value: " + item.getString()); } else { // Process <input type="file"> here. InputStream movie = item.getInputStream(); byte[] bytes = IOUtils.toByteArray(movie); Byte[] clipBytes = ArrayUtils.toObject(bytes); Clip clip = new Clip(Long.valueOf(0), i); clips.add(i, clip); listData.add(i, clipBytes); i++; // w.print(movie); } } } catch (FileUploadException e) { log.error("Error uploading file, please try again."); request.setAttribute("error", "Error uploading file, please try again"); request.setAttribute("token", mapValues.get("token")); request.getRequestDispatcher("/upload.jsp").forward(request, response); } //Sets duration of clip and saves clipdata for (int j = 0; j < clips.size(); j++) { int duration = timeToInt(mapValues.get("clipduration" + j)); clips.get(j).setDuration(Long.valueOf(duration)); ClipData clipData = new ClipData(listData.get(j), clips.get(j)); try { vManager.uploadClip(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), clipData); log.info("ClipData uploader!"); } catch (InvalidTokenException e) { log.error("Unknown user, please try again."); request.setAttribute("error", "Unknown user, please try again."); request.getRequestDispatcher("/index.jsp").forward(request, response); return; } } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date endDate = null; Date startDate = null; Date premiereDate = null; try { endDate = formatter.parse(mapValues.get("endDate")); startDate = formatter.parse(mapValues.get("startDate")); premiereDate = formatter.parse(mapValues.get("premiere")); } catch (ParseException e) { log.error("Error parsing date"); request.setAttribute("token", mapValues.get("token")); request.setAttribute("error", "Invalid date, please try again"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return; } License license = new License(false, Long.valueOf(0), mapValues.get("licenseDescription"), endDate, Long.valueOf(mapValues.get("maxViews")), Long.valueOf(1), startDate, mapValues.get("licenseName")); List<License> licenses = new ArrayList<License>(); licenses.add(license); ArrayList<String> cast = new ArrayList<String>(); cast.add(mapValues.get("actor")); Movie movie = new Movie(cast, clips, mapValues.get("director"), Long.valueOf(mapValues.get("duration")), false, mapValues.get("genre"), licenses, premiereDate, mapValues.get("title")); try { vManager.uploadMovie(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), movie); log.info("Movie uploaded!"); } catch (InvalidTokenException e) { log.error("Unknown user, please try again."); request.setAttribute("error", "Unknown user, please try again."); request.getRequestDispatcher("/index.jsp").forward(request, response); return; } request.setAttribute("message", "Movie uploaded successfully."); request.setAttribute("token", mapValues.get("token")); request.getRequestDispatcher("/upload.jsp").forward(request, response); }
From source file:net.duckling.ddl.web.controller.AttachmentController.java
/** * DDL??/*from w w w . j a v a2 s. com*/ * @param request * @return * @throws IOException * @throws ServletException */ private boolean checkUserConflict(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException { String code = request.getParameter("code"); AuthorizationCode ac = authorizationCodeService.getCode(code); String uid = VWBSession.getCurrentUid(request); int tid = VWBContext.getCurrentTid(); boolean userConflict = true; if (ac != null && ac.isAvailable()) { if (!ac.getUid().equals(uid)) { updateLoginUser(request); } userConflict = false; } else { if (VWBSession.findSession(request).isAuthenticated()) { String auth = authorityService.getTeamAuthority(tid, uid); if ("forbid".equals(auth)) { String url = urlGenerator.getAbsoluteURL(UrlPatterns.LOGIN, null, null) + "?" + Attributes.REQUEST_URL + "=" + URLEncoder.encode(request.getRequestURL().toString(), "utf-8"); VWBSession.findSession(request).setAttribute(Attributes.REQUEST_URL, url); request.setAttribute("logout", "/system/logout"); request.getRequestDispatcher("/jsp/aone/tag/resousePreviewError.jsp").forward(request, resp); } else { userConflict = false; } } else { VWBSession.findSession(request).setAttribute(Attributes.REQUEST_URL, request.getRequestURL().toString()); resp.sendRedirect("/system/login"); } } return userConflict; }
From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java
private void create2(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(false); // Inputs de formulario UploadFile uf = null;/*from ww w.j a v a2 s .c om*/ uf = new UploadFile(request); Particular demandante = (Particular) session.getAttribute("usuario"); //demandante = new ParticularDAO().read(demandante.getIdParticular()); String numeroDemanda = ToolBox.createNumeroDemanda(); String nombre = uf.getFormField("nombre"); String descripcion = uf.getFormField("descripcion"); int estado = 1; // Validacin de campos if (numeroDemanda == null || numeroDemanda.equals("") || nombre == null || nombre.equals("") || descripcion == null || descripcion.equals("") || uf.getFiles().size() < 1) { try { request.setAttribute("messages", new Messages().getClientMessage("error", 1)); request.getRequestDispatcher("Demanda?action=form").forward(request, response); } catch (ServletException ex) { Logger.getLogger(DemandaServlet.class.getName()).log(Level.SEVERE, null, ex); } } else { // Tiempo Date fechaCreacion = ToolBox.dateFormat(new Date()); // Obtenemos 3 magistrados menos ocupados MagistradoDAO madao = new MagistradoDAO(); Set<Magistrado> magistrados = madao.get3Magistrado(); if (magistrados == null || magistrados.size() < 3) { magistrados = madao.readAll3(); } // Objetos de TIEMPO Tiempo tiempo = new Tiempo(); tiempo.setFechaCreacion(fechaCreacion); TiempoDAO tidao = new TiempoDAO(); tidao.create(tiempo); // Objeto DEMANDA Demanda demanda = new Demanda(); demanda.setParticularByIdParticularDemandante(demandante); demanda.setTiempo(tiempo); demanda.setNumeroDemanda(numeroDemanda); demanda.setNombreDemanda(nombre); demanda.setDescripcion(descripcion); demanda.setEstado(estado); demanda.setMagistrados(magistrados); // Asignamos demanda a Msgistrados // for (Magistrado mag : magistrados) { // MagistradoDAO madao2 = new MagistradoDAO(); // // mag.setDemandas((Set<Demanda>) demanda); // // madao2.update(mag); // } // Guardamos demanda DemandaDAO dedao = new DemandaDAO(); if (!dedao.create(demanda)) { try { request.setAttribute("messages", new Messages().getClientMessage("error", 4)); request.getRequestDispatcher("Demanda?action=form").forward(request, response); } catch (ServletException ex) { Logger.getLogger(DemandaServlet.class.getName()).log(Level.SEVERE, null, ex); } } else { // Guardamos los documentos String sala = "s1"; //uf.saveAllFiles(this.getServletContext().getRealPath(""), sala, numeroDemanda); for (FileItem fi : uf.getFiles()) { // Documentos Documento documento = new Documento(); documento.setDemanda(demanda); documento.setParticular(demandante); documento.setFechaCarga(ToolBox.dateFormat(new Date())); documento.setRuta( uf.saveFile(fi, this.getServletContext().getRealPath(""), sala, numeroDemanda)); documento.setEstado(1); documento.setNombre(fi.getName()); DocumentoDAO dodao = new DocumentoDAO(); dodao.create(documento); } Mail mail = new Mail(demandante.getCatalogousuarios().getCorreo(), "Demanda creada", "Nmero de demanda: " + numeroDemanda); //Mail mail = new Mail("eddy_wallace@hotmail.com", "Demanda creada", "Nmero de demanda: " + numeroDemanda); //mail.sendMail(); try { request.setAttribute("messages", new Messages().getClientMessage("ok", 5)); request.getRequestDispatcher("Demanda?action=form").forward(request, response); } catch (ServletException ex) { Logger.getLogger(DemandaServlet.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:org.guanxi.idp.service.Logout.java
/** * Does the logging out. The method looks for the user's IdP cookie in the * request and if it finds it, it extracts the corresponding GuanxiPrincipal * and sends it to SSO.logout() for processing. * /*from w w w .java2 s .c o m*/ * @param request * Standard HttpServletRequest * @param response * Standard HttpServletRequest * @throws ServletException * if an error occurrs * @throws IOException * if an error occurrs */ public void processLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cookieName = getCookieName(); boolean loggedOut = false; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int c = 0; c < cookies.length; c++) { if (cookies[c].getName().equals(cookieName)) { // Retrieve the principal from the servlet context... GuanxiPrincipal principal = (GuanxiPrincipal) servletContext .getAttribute(cookies[c].getValue()); // ...and get rid of it if (principal != null) { servletContext.setAttribute(principal.getUniqueId(), null); } loggedOut = true; } } } /* * Only display the logout page if we're not in passive mode. What this * means is if we're in passive mode (passive = yes) then we're most likely * embedded in an application, which has it's own logout page. */ if (!passive) { if (loggedOut) request.setAttribute("LOGOUT_MESSAGE", messageSource.getMessage("idp.logout.successful", null, request.getLocale())); else request.setAttribute("LOGOUT_MESSAGE", messageSource.getMessage("idp.logout.unsuccessful", null, request.getLocale())); request.getRequestDispatcher(logoutPage).forward(request, response); } }
From source file:com.openedit.generators.FilterGenerator.java
public void generate(WebPageRequest inContext, Page inPage, Output inOut) throws OpenEditException { HttpServletRequest httpRequest = inContext.getRequest(); HttpServletResponse httpResponse = inContext.getResponse(); Page page = (Page) inContext.getPageValue("page"); //load the standard context objects httpRequest.setAttribute("context", inContext); httpRequest.setAttribute("pages", inContext.getPageStreamer()); httpRequest.setAttribute("content", inContext.getContentPage()); /* I commented this out since it conflics with existing JSP pages. Blojsom has its own "page" variable, get stuff from the context for (Iterator iter = inContext.getPageMap().entrySet().iterator(); iter.hasNext();) {//from w ww . j a v a 2 s .c om Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); httpRequest.setAttribute(key, inContext.getPageValue(key)); } */ DecoratedServletResponse response = new DecoratedServletResponse(httpResponse, new DecoratedServletOutputStream(inOut)); DecoratedServletRequest newrequest = new DecoratedServletRequest(httpRequest); String requestPath = page.getContentItem().getActualPath(); newrequest.setrequestURI(requestPath); try { inOut.getWriter().flush(); //URLUtilities urls = (URLUtilities)inContext.getPageValue(PageRequestKeys.URL_UTILITIES); if (requestPath.endsWith(".jsp")) { //A dispatcherallow us to use the base directory and draft modes RequestDispatcher jspDispatcher = httpRequest.getRequestDispatcher(requestPath); jspDispatcher.include(newrequest, response); //This only applies for jsp pages. } else { FilterChain chain = (FilterChain) httpRequest.getAttribute("servletchain"); chain.doFilter(newrequest, response); //This will capture output to our existing output class } inOut.getWriter().flush(); } catch (ServletException ex) { throw new OpenEditException(ex); } catch (IOException ex) { throw new OpenEditException(ex); } }
From source file:com.edgenius.wiki.webapp.servlet.InstallServlet.java
/** * @param request/*from w w w . j a v a 2s .c om*/ * @param response * @throws ServletException * @throws IOException */ private void viewDBCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //echo back value Server server = (Server) request.getSession().getAttribute("server"); String dbType = server.getDbType(); request.setAttribute("dbType", dbType); request.setAttribute("rootUser", ""); request.setAttribute("rootPassword", ""); request.setAttribute("host", DBLoader.detectHost(dbType, server.getDbUrl())); request.setAttribute("dbname", DBLoader.detectDBName(dbType, server.getDbUrl())); request.setAttribute("adminDBUrl", server.getDbUrl()); request.setAttribute("username", server.getDbUsername()); request.setAttribute("password", server.getDbPassword()); request.getRequestDispatcher("/WEB-INF/pages/install/createdb.jsp").forward(request, response); }
From source file:com.darksky.seller.SellerServlet.java
/** * /* w w w. j a v a 2s .c om*/ * @param request * @param response * @throws ServletException * @throws IOException */ public void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(); System.out.println("----------------------------seller logOut--------------------"); System.out.println("seller logOut"); request.getSession().removeAttribute("user"); request.getSession().removeAttribute("order"); request.getSession().removeAttribute("shop"); System.out.println("----------------------------seller logOut--------------------"); System.out.println(); request.getRequestDispatcher("HomeServlet?method=showShops").forward(request, response); }
From source file:com.alfaariss.oa.profile.aselect.processor.handler.BrowserHandler.java
/** * Handle the redirect sent by the application to show the user information page. * <br>/*from w ww. ja v a2 s .co m*/ * Redirects the user to the WebSSO. * @param oServletRequest HTTP servlet request object * @param oServletResponse HTTP servlet response object * @throws ASelectException if request handling failed */ public void userinformation(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse) throws ASelectException { try { if (_sWebSSOUrl != null) { _logger.debug("Redirect to web sso: " + _sWebSSOUrl); try { oServletResponse.sendRedirect(_sWebSSOUrl); } catch (Exception e) { _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null, oServletRequest.getRemoteAddr(), null, this, "user information")); _logger.fatal("Internal error during user information request process", e); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } } else { _logger.debug("Forward to web sso: " + _sWebSSOPath); RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(_sWebSSOPath); if (oDispatcher == null) { _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null, oServletRequest.getRemoteAddr(), null, this, "user information")); _logger.warn("There is no requestor dispatcher supported with name: " + _sWebSSOPath); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } oDispatcher.forward(oServletRequest, oServletResponse); } } catch (ASelectException e) { throw e; } catch (Exception e) { _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null, oServletRequest.getRemoteAddr(), null, this, "user information")); _logger.fatal("Internal error during user information request process", e); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } }