List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:net.duckling.ddl.web.controller.AttachmentController.java
@RequestMapping public ModelAndView display(HttpServletRequest request, HttpServletResponse response, @PathVariable("rid") Integer rid) throws IOException, ServletException { String redirect = request.getParameter("redirect"); if (StringUtils.isEmpty(redirect)) { String url = request.getRequestURL().toString() + "?" + request.getQueryString() + "&redirect=redirect"; request.setAttribute("url", url); request.setAttribute("noHref", "no"); request.getRequestDispatcher("/jsp/aone/hash/dealHashRequest.jsp").forward(request, response); return null; }/*ww w . j a va 2 s . c o m*/ if (checkUserConflict(request, response)) { return null; } Resource resource = resourceService.getResource(rid); if (resource == null || resource.getTid() != VWBContext.getCurrentTid() || resource.isDelete()) { ModelAndView m = dealResourceRemove(request, resource); if (m != null) { return m; } notFound(request, response, true); return null; } ModelAndView mv = null; if (resource.isFile()) { mv = dealFile(request, response, resource); } else { notFound(request, response, true); return null; } mv.addObject("pageType", "list"); if (resource.isAvailable()) { mv.addObject("resourePath", getParentPath(resource)); } mv.addObject("teamUrl", urlGenerator.getURL(resource.getTid(), UrlPatterns.T_LIST, null, null)); mv.addObject("teamHome", urlGenerator.getURL(resource.getTid(), UrlPatterns.T_TEAM_HOME, null, null)); addMyTeam(request, mv); return mv; }
From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java
/** * Processes the request made from the HTML visual interface of Strabon Endpoint. * // ww w. j a v a 2 s . c o m * @param request * @param response * @throws ServletException * @throws IOException */ private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher; // check whether Update submit button was fired String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit"); if (reqFuncionality.equals("Update")) { // get the dispatcher for forwarding the rendering of the response dispatcher = request.getRequestDispatcher("/Update"); dispatcher.forward(request, response); } else { String query = URLDecoder.decode(request.getParameter("query"), "UTF-8"); String format = request.getParameter("format"); String handle = request.getParameter("handle"); String maxLimit = request.getParameter("maxLimit"); // get stSPARQLQueryResultFormat from given format name TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format); if (query == null || format == null || queryResultFormat == null) { dispatcher = request.getRequestDispatcher("query.jsp"); request.setAttribute(ERROR, PARAM_ERROR); dispatcher.forward(request, response); } else { query = strabonWrapper.addLimit(query, maxLimit); if ("download".equals(handle)) { // download as attachment ServletOutputStream out = response.getOutputStream(); response.setContentType(queryResultFormat.getDefaultMIMEType()); response.setHeader("Content-Disposition", "attachment; filename=results." + queryResultFormat.getDefaultFileExtension() + "; " + queryResultFormat.getCharset()); try { strabonWrapper.query(query, format, out); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.print(ResponseMessages.getXMLHeader()); out.print(ResponseMessages.getXMLException(e.getMessage())); out.print(ResponseMessages.getXMLFooter()); } out.flush(); } else if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle)) && (queryResultFormat == stSPARQLQueryResultFormat.KML || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) { // show map (only valid for KML/KMZ) // get dispatcher dispatcher = request.getRequestDispatcher("query.jsp"); // re-assign handle request.setAttribute("handle", handle); SecureRandom random = new SecureRandom(); String temp = new BigInteger(130, random).toString(32); // the temporary KML/KMZ file to create in the server String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension(); ; try { Date date = new Date(); // get the absolute path of the temporary directory if (!request.getParameter("handle").toString().contains("timemap")) { tempDirectory = appName + "-temp"; basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/"; // fix the temporary directory for this web application FileUtils.forceMkdir(new File(basePath)); @SuppressWarnings("unchecked") Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false); while (it.hasNext()) { File tbd = new File((it.next()).getAbsolutePath()); if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) { FileUtils.forceDelete(new File(tbd.getAbsolutePath())); } } } else { //timemap case tempDirectory = "js/timemap"; basePath = context.getRealPath("/") + tempDirectory + "/"; // fix the temporary directory for this web application } // fix the temporary directory for this web application // create temporary KML/KMZ file File file = new File(basePath + tempKMLFile); // if file does not exist, then create it if (!file.exists()) { file.createNewFile(); } try { // query and write the result in the temporary KML/KMZ file FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile); strabonWrapper.query(query, format, fos); fos.close(); if (request.getParameter("handle").toString().contains("timemap")) { request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile); } else { request.setAttribute("pathToKML", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + tempDirectory + "/" + tempKMLFile); } } catch (MalformedQueryException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage()); request.setAttribute(ERROR, e.getMessage()); } catch (Exception e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); request.setAttribute(ERROR, e.getMessage()); } dispatcher.forward(request, response); } catch (IOException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); } } else { // "plain" is assumed as the default dispatcher = request.getRequestDispatcher("query.jsp"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { strabonWrapper.query(query, format, bos); if (format.equals(Common.getHTMLFormat())) { request.setAttribute(RESPONSE, bos.toString()); } else if (format.equals(Format.PIECHART.toString()) || format.equals(Format.AREACHART.toString()) || format.equals(Format.COLUMNCHART.toString())) { request.setAttribute("format", "CHART"); request.setAttribute(RESPONSE, strabonWrapper.getgChartString()); } else { request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString())); } } catch (MalformedQueryException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage()); request.setAttribute(ERROR, e.getMessage()); } catch (Exception e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); request.setAttribute(ERROR, e.getMessage()); } finally { dispatcher.forward(request, response); } } } } }
From source file:com.gunjan.businessLayer.dictServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//www.j a va2s .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 { String queryWord = request.getParameter("word").trim(); // System.out.println("queryword----------------" + queryWord); // DBConnection conn = DBConnection.getConnection(); // System.out.println("conn ------------------------" + conn); // ArrayList<Definition> wordDefinitions = conn.getDefinition(queryWord); // if (wordDefinitions != null) { // String definitions = wordDefinitions.stream().map(d -> "<br>" + d).collect(Collectors.joining()); // request.setAttribute("definitions", definitions); // } String JSONObject = getJSONObjectForWord(queryWord); request.getSession().setAttribute("JSONObject", JSONObject); RequestDispatcher dispatch = request.getRequestDispatcher("getJSON.jsp"); dispatch.forward(request, response); }
From source file:atd.home.BlogPost.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w ww . j a v a2s. com Class.forName("org.apache.commons.lang3.StringEscapeUtils"); } catch (ClassNotFoundException e) { Logger.getLogger("atd.log").warning("Kan niet lib importeren"); e.printStackTrace(); } String bericht = req.getParameter("bericht"); java.util.Date dt = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(dt); User user = (User) req.getSession().getAttribute("username"); // Deze moet later verwerkt worden in KlantenBinding //BerichtenService.setBericht(StringEscapeUtils.escapeHtml4(bericht), currentTime, user); RequestDispatcher rd = null; Logger.getLogger("atd.log").info("Bericht: " + bericht + " door " + user.getNaam() + " is geplaatst"); rd = req.getRequestDispatcher("/index.jsp"); rd.forward(req, resp); }
From source file:com.alfaariss.oa.authentication.remote.aselect.selector.DefaultSelector.java
private void forwardUser(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession, List<ASelectIDP> listOrganizations, String sMethodName, List<Warnings> oWarnings) throws OAException { try {/*ww w . j a v a 2s . co m*/ //set request attributes oRequest.setAttribute(ISession.ID_NAME, oSession.getId()); oRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale()); oRequest.setAttribute(REQUEST_PARAM_ORGANIZATIONS, listOrganizations); if (oWarnings != null) oRequest.setAttribute(DetailedUserException.DETAILS_NAME, oWarnings); oRequest.setAttribute(IWebAuthenticationMethod.AUTHN_METHOD_ATTRIBUTE_NAME, sMethodName); oRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer()); RequestDispatcher oDispatcher = oRequest.getRequestDispatcher(_sTemplatePath); if (oDispatcher == null) { _logger.warn("There is no request dispatcher supported with name: " + _sTemplatePath); throw new OAException(SystemErrors.ERROR_INTERNAL); } _logger.debug("Forward user to: " + _sTemplatePath); oDispatcher.forward(oRequest, oResponse); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during forward", e); throw new OAException(SystemErrors.ERROR_INTERNAL, e); } }
From source file:Controller.ControllerCustomers.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a2 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"); PrintWriter out = response.getWriter(); try { String action = request.getParameter("action"); if (action.equals("Login")) { String user = request.getParameter("txtId"); String pass = request.getParameter("txtpass"); Customers ct = new Customers(); String anh = ct.anh(user); boolean check = ct.checkLogin(user, pass); String url = "error.jsp"; if (check) { if (ct.role(user)) { RequestDispatcher rd = request.getRequestDispatcher("Admin.jsp"); rd.forward(request, response); } else { url = "index_Cus_2.jsp"; HttpSession session = request.getSession(true); session.setAttribute("User", user); session.setAttribute("Image", anh); // <% CartDao listsp = new CartDao(); List<Cart> list = CartDao.layDanhSachCart(user); session.setAttribute("list", list); // %> } } RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } else if (action.equals("FIND")) { String username = request.getParameter("txtusername"); CustomerDAO cusdao = new CustomerDAO(); List<Customer> list = new ArrayList<Customer>(); list = cusdao.layDanhSachKhachHang(username); request.setAttribute("listKH", list); RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp"); rd.forward(request, response); } else if (action.equals("DELETE")) { String username = request.getParameter("txtusername"); boolean delete = CustomerDAO.XoaKhachHang(username); if (delete) { RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp"); rd.forward(request, response); } } else if (action.equals("Edit")) { String username = request.getParameter("txtusername"); String password = request.getParameter("txtpassword"); String hoten = request.getParameter("txthoten"); String gioitinh = request.getParameter("txtgioitinh"); String email = request.getParameter("txtemail"); String role = request.getParameter("txtrole"); String anh = request.getParameter("txtanh"); Customer cus = new Customer(username, password, hoten, gioitinh, email, role, anh); request.setAttribute("Cus", cus); RequestDispatcher rd = request.getRequestDispatcher("editCustomer.jsp"); rd.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.artifactory.webapp.servlet.RepoFilter.java
private void doRepoListing(HttpServletRequest request, HttpServletResponse response, String servletPath, ArtifactoryRequest artifactoryRequest) throws ServletException, IOException { log.debug("Forwarding internally to an apache-style listing page."); if (!servletPath.endsWith("/")) { response.sendRedirect(HttpUtils.getServletContextUrl(request) + servletPath + "/"); return;/*ww w.j a v a 2 s.co m*/ } request.setAttribute(ATTR_ARTIFACTORY_REPOSITORY_PATH, artifactoryRequest.getRepoPath()); request.setAttribute(ATTR_ARTIFACTORY_REQUEST_PROPERTIES, artifactoryRequest.getProperties()); RequestDispatcher dispatcher = request.getRequestDispatcher("/ui/nativeBrowser"); dispatcher.forward(request, response); }
From source file:edu.isi.wings.portal.classes.Config.java
public void showError(HttpServletRequest request, HttpServletResponse response, String message) { try {/*from w ww. ja va2s .com*/ response.setContentType("text/html"); request.setAttribute("message", message); request.setAttribute("nohome", true); request.getRequestDispatcher("index.jsp").include(request, response); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.gs.config.ItemBasedAuthenticationFailureHandler.java
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) exception .getAuthentication();//from w w w .j av a 2 s . c om //System.out.println("Mensaje del error: "+exception.getMessage()); // PrincipalsessionInformaction user = request.getUserPrincipal(); System.out.println("-----------------------------INTENTO FALLIDO-----------------------------"); //Causas de la autenticacin fallida if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) { // System.out.println("INTENTO FALLIDO: El usuario no est registrado en la base de datos "); request.setAttribute("ERRORSESSION", "Usuario no registrado, verifique con el administrador"); request.getRequestDispatcher("login?err=1").forward(request, response); //response.sendRedirect("login?err=1"); } else if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) { sessionFailDaoImp.insertUserSessionFail(user.getName(), request.getLocalAddr()); usuarioConIntentoFallido.addIntentoUsuario(user.getName()); // System.out.println("INTENTO FALLIDO: Creedenciales erroneas"); request.setAttribute("ERRORSESSION", "Contrasea incorrecta, intente nuevamente"); request.getRequestDispatcher("login?err=1").forward(request, response); //response.sendRedirect("login?err=2"); } else if (exception.getClass().isAssignableFrom(DisabledException.class)) { // System.out.println("INTENTO FALLIDO: Usuario desabilitado"); request.setAttribute("ERRORSESSION", "Usuario deshabilitado, verifique con el administrador"); request.getRequestDispatcher("login?err=1").forward(request, response); //response.sendRedirect("login?err=3"); } else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) { // System.out.println("INTENTO FALLIDO: Usuario ya logeado"); request.setAttribute("ERRORSESSION", "Ya existe una sesin abierta con este usuario"); request.getRequestDispatcher("login?err=1").forward(request, response); //response.sendRedirect("login?err=4"); } else if (exception.getClass().isAssignableFrom(IntentLimitExceeded.class)) { // System.out.println("INTENTO FALLIDO: NMERO DE INTENTOS EXCEDIDOS"); //Elimino al usuario de la listo de los intentos y se agrega a la lista de usuarios bloqueados usuarioConIntentoFallido.removeUsuario(user.getName()); //Se crea el hilo para desbloquear al usuario listUsersLockoutIntentFail.addBlockUserFail(user.getName(), tiempoLockout); //request.setAttribute("ERRORSESSION", "Ha excedido el lmite de intentos. Por favor espere unos minutos e intente nuevamente"); request.getRequestDispatcher("intentlimit").forward(request, response); } else { // System.out.println("INTENTO FALLIDO: NO SE QUE PASO"); request.setAttribute("ERRORSESSION", "No ha sido posible iniciar sesin"); request.getRequestDispatcher("login?err=1").forward(request, response); } }
From source file:org.guanxi.sp.engine.security.GuardVerifier.java
/** * Blocks Guard access to a service until the Guard can be verified. * * @param request Standard HttpServletRequest * @param response Standard HttpServletResponse * @param object handler/*from w ww. j ava2 s . c om*/ * @return true if the caller is authorised to use the service * @throws Exception if an error occurs */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String guardID = request.getParameter(Guanxi.WAYF_PARAM_GUARD_ID); String sessionID = request.getParameter(Guanxi.WAYF_PARAM_SESSION_ID); if ((guardID == null) || (sessionID == null)) { logger.error("Cant' verify Guard due to missing parameter"); request.setAttribute("error", messages.getMessage("engine.error.missing.guard.verification.parameter", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.missing.guard.verification.parameter", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } EntityDescriptorType guardEntityDescriptor = (EntityDescriptorType) servletContext.getAttribute(guardID); if (guardEntityDescriptor == null) { logger.error("Guard '" + guardID + "' not found in metadata repository"); request.setAttribute("error", messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } Config config = (Config) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_CONFIG); if (config == null) { logger.error("Guard '" + guardID + "' wants to talk but Engine hasn't finished initialisation"); request.setAttribute("error", messages.getMessage("engine.error.not.initialised", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.not.initialised", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } // Load the GuanxiGuardService node from the metadata GuardRoleDescriptorExtensions guardNativeMetadata = Util.getGuardNativeMetadata(guardEntityDescriptor); // Build the REST URL to verify the Guard's session String queryString = guardNativeMetadata.getVerifierURL() + "?" + Guanxi.SESSION_VERIFIER_PARAM_SESSION_ID + "=" + sessionID; // If we haven't already checked the Guard for secure comms, do it now if (servletContext.getAttribute(guardID + "SECURE_CHECK_DONE_SP") == null) { // Load up the Guard's native metadata... GuardRoleDescriptorExtensions guardExt = Util.getGuardNativeMetadata(guardEntityDescriptor); // ...and see if it's using HTTPS try { if (Util.isGuardSecure(guardExt)) { logger.info("Probing for Guard certificate for : " + guardID); /* If the Guard is using HTTPS then we'll need to connect to it, extract it's * certificate and add it to our truststore. To do that, we'll need to use our * own keystore to let the Guard authenticate us. */ EntityConnection guardConnection = new EntityConnection(queryString, config.getCertificateAlias(), // alias of cert config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(), config.getTrustStorePassword(), EntityConnection.PROBING_ON); X509Certificate guardX509 = guardConnection.getServerCertificate(); // We've got the Guard's X509 so add it to our truststore... KeyStore engineTrustStore = KeyStore.getInstance("jks"); engineTrustStore.load(new FileInputStream(config.getTrustStore()), config.getTrustStorePassword().toCharArray()); // ...under it's Subject DN as an alias... engineTrustStore.setCertificateEntry(guardID, guardX509); // ...and rewrite the trust store engineTrustStore.store(new FileOutputStream(config.getTrustStore()), config.getTrustStorePassword().toCharArray()); // Mark Guard as having been checked for secure comms servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "SECURE"); logger.info("Added : " + guardID + " to truststore"); } else { // Mark Guard as having been checked for secure comms servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "NOT_SECURE"); } } catch (Exception e) { logger.error("Failed to probe Guard : " + guardID + " for cert : ", e); request.setAttribute("error", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } } // Verify that the Guard actually sent the request String verificationResult = null; try { EntityConnection verifierService = new EntityConnection(queryString, config.getCertificateAlias(), // alias of cert config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(), config.getTrustStorePassword(), EntityConnection.PROBING_OFF); verifierService.setDoOutput(true); verifierService.connect(); verificationResult = verifierService.getContentAsString(); } catch (GuanxiException ge) { logger.error("Guard '" + guardID + "' error during verification : ", ge); request.setAttribute("error", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } // Did the Guard verify the session? if (!verificationResult.equals(Guanxi.SESSION_VERIFIER_RETURN_VERIFIED)) { logger.error("Guard '" + guardID + "' error during verification : " + verificationResult); request.setAttribute("error", messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } /* Convert the Guard's session ID to an Engine session ID and store the Guard's GuanxiGuardService * node under it. */ servletContext.setAttribute(sessionID.replaceAll("GUARD", "ENGINE"), guardEntityDescriptor); return true; }