List of usage examples for javax.servlet.http HttpServletResponse sendRedirect
public void sendRedirect(String location) throws IOException;
From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java
@Override public void doAuthenticateAction(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final Token token, final Boolean isError) throws IOException { httpResponse.sendRedirect(getAuthenticationEndPoint(httpRequest, token, isError)); }
From source file:cn.vlabs.duckling.vwb.VWBDriverServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { URLParser info = URLParser.getParser(request); if (info.hasMoreSlash()) { response.sendRedirect(buildURL(info, request)); return;//from w w w . j ava2 s . c o m } SiteMetaInfo site = findSiteById(request, info.getSiteId()); if (site == null) { site = findSiteByDomain(request); } if (site == null) { log.info("Neither site find by site id or domain. redirect to default site."); site = container.getSite(VWBContainer.ADMIN_SITE_ID); response.sendRedirect(getFrontPage(request)); return; } if (requireRedirect(request, info, site.getId())) { response.sendRedirect(getFrontPage(request)); return; } if (info.isPlainURL()) { // Plain URL just forward. // support for Site id based url (login/logout/JSON-RPC etc.). if (info.getPage() != null) { RequestDispatcher dispatcher = request.getRequestDispatcher(info.getPage()); dispatcher.forward(request, response); return; } } if (info.isSimpleURL()) { processSimpleURL(info, request, response); return; } if (info.getPage() == null) { response.sendRedirect(getFrontPage(request)); return; } // Proceeding viewport... int vid = Constant.DEFAULT_FRONT_PAGE; vid = Integer.parseInt(info.getPage()); Resource vp = VWBContainerImpl.findContainer().getResourceService().getResource(site.getId(), vid); if (vp == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } try { if (showWelcome(request, site, vid)) { vid = Constant.WELCOME_FRONT_PAGE; vp = VWBContainerImpl.findContainer().getResourceService().getResource(site.getId(), vid); } } catch (NumberFormatException e) { response.sendRedirect(getFrontPage(request)); return; } request.setAttribute("contextPath", request.getContextPath()); try { IRequestMapper mapper = container.getMapFactory().getRequestMapper(vp.getType()); if (mapper != null) { log.debug(vp.getType() + " is requested."); fetcher.saveToSession(request); mapper.map(vp, info.getParams(), request, response); } else { log.debug("not support type is requested."); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } catch (ServletException e) { if (e.getRootCause() != null) { sendError(request, response, e.getRootCause()); } else sendError(request, response, e); } catch (Throwable e) { sendError(request, response, e); } }
From source file:controlador.SerPartido.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request// w w w. j a va2s .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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); PrintWriter out = response.getWriter(); //eliminar registro de partido if (request.getParameter("idPartido") != null) { int id = Integer.parseInt(request.getParameter("idPartido")); if (PartidoDTO.eliminarPartido(id)) { response.sendRedirect(this.redireccionJSP); } else { out.print("Error al eliminar"); } } }
From source file:com.recipes.controller.Recipes.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . 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 { response.setContentType("text/html;charset=UTF-8"); DAO dao = new DAO(); HttpSession session = request.getSession(true); if (request.getParameter("add") != null) { response.sendRedirect("addRecipe.jsp"); } else if (request.getParameter("insert") != null) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { // fayl yoxdur mesaj return; } String title = "";//String deyiwenleri gotururuy String article = ""; String category = ""; String prepareRules = ""; String image = ""; List<String> composition = new ArrayList<>(); String cook_time = ""; String total_time = ""; String prep_time = ""; while (it.hasNext()) { // eger file varsa FileItem fileItem = it.next(); // iteratorun next metodu cagrilir boolean isFormField = fileItem.isFormField(); // isformField-input yoxlanilirki if (isFormField) { // eger isFormFIelddise switch (fileItem.getFieldName()) { case "title": title = fileItem.getString("UTF-8").trim(); break; case "category": category = fileItem.getString("UTF-8").trim(); break; case "article": article = fileItem.getString("UTF-8").trim(); break; case "prepareRules": prepareRules = fileItem.getString("UTF-8").trim(); break; case "image": image = fileItem.getString("UTF-8").trim(); break; case "tags": composition.add(fileItem.getString("UTF-8").trim()); break; case "prep_time": prep_time = fileItem.getString("UTF-8").trim(); break; case "cook_time": cook_time = fileItem.getString("UTF-8").trim(); break; case "total_time": total_time = fileItem.getString("UTF-8").trim(); break; } } else { if (fileItem.getFieldName().equals("image")) { if (!fileItem.getString("UTF-8").trim().equals("")) { image = fileItem.getName(); image = dao.generateCode() + image; String relativeWebPath = "photos"; String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath); File file = new File(absoluteDiskPath + "/", image); fileItem.write(file); } } } } Recipe recipe = new Recipe(); recipe.setArticle(article); recipe.setCategory(category); String comps = ""; for (String c : composition) comps += c + ","; if (comps.contains(",")) comps = comps.substring(0, comps.length() - 1); recipe.setComposition(comps); if (image.isEmpty()) { image = "defaultrecipe.jpg"; } recipe.setImage(image); recipe.setLike_count(0); recipe.setPrepared_rules(prepareRules); recipe.setTitle(title); recipe.setUser_id(Integer.parseInt(session.getAttribute("user_id").toString())); recipe.setVisible(1); recipe.setPrep_time(prep_time); recipe.setCook_time(cook_time); recipe.setTotal_time(total_time); dao.insertRecipe(recipe); response.sendRedirect("addRecipe.jsp?success="); } catch (Exception e) { e.printStackTrace(System.out); } } else if (request.getParameter("id") != null) { response.sendRedirect("recipeDetails.jsp?id=" + request.getParameter("id")); } else { response.sendRedirect("index.jsp"); } }
From source file:edu.hawaii.its.hudson.security.Cas1SecurityRealm.java
@Override public Filter createFilter(FilterConfig filterConfig) { AuthenticationFilter authenticationFilter = new AuthenticationFilter(); authenticationFilter.setIgnoreInitConfiguration(true); // configuring here, not in web.xml authenticationFilter.setRenew(forceRenewal); authenticationFilter.setGateway(false); authenticationFilter.setCasServerLoginUrl(casServerUrl + "/login"); authenticationFilter.setServerName(hudsonHostName); Cas10TicketValidationFilter validationFilter = new Cas10TicketValidationFilter(); validationFilter.setIgnoreInitConfiguration(true); // configuring here, not in web.xml validationFilter.setRedirectAfterValidation(true); validationFilter.setServerName(hudsonHostName); validationFilter.setTicketValidator(new AbstractCasProtocolUrlBasedTicketValidator(casServerUrl) { protected String getUrlSuffix() { return "validate"; // version 1 protocol }//from w ww. j av a 2 s . c o m protected Assertion parseResponseFromServer(final String response) throws TicketValidationException { if (!response.startsWith("yes")) { throw new TicketValidationException("CAS could not validate ticket."); } try { final BufferedReader reader = new BufferedReader(new StringReader(response)); String mustBeYes = reader.readLine(); assert mustBeYes.equals("yes") : mustBeYes; String username = reader.readLine(); // parse optional extra validation attributes Collection roles = parseRolesFromValidationResponse(getParsedScript(), response); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AUTH_KEY, new Cas1Authentication(username, roles)); // Acegi Authentication // CAS saves this Assertion in the session; we'll use the Authentication it's carrying. return new AssertionImpl(new AttributePrincipalImpl(username), attributes); } catch (final IOException e) { throw new TicketValidationException("Unable to parse CAS response.", e); } } }); Filter casToAcegiContext = new OnlyDoFilter() { /** * Gets the authentication out of the session and puts it in Acegi's ThreadLocal on every request. * If we've made it this far down this FilterChain without a redirect, * then there must be a session with an authentication in it. * Using an Acegi filter to do this would require implementing more of the Acegi framework. */ public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpSession session = request.getSession(false); final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); try { Cas1Authentication auth = (Cas1Authentication) assertion.getAttributes().get(AUTH_KEY); SecurityContextHolder.getContext().setAuthentication(auth); filterChain.doFilter(servletRequest, servletResponse); } finally { SecurityContextHolder.getContext().setAuthentication(null); } } }; Filter jettyJsessionidRedirect = new OnlyDoFilter() { private final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper(); /** * Redirects to remove a jsessionid that a servlet container leaves in the URI if it's also in a cookie. * Jetty's getRequestURI() fails to remove the jsessionid (whether or not it's also in a cookie), * and this messes up Hudson's Stapler (as of version 1.323, at least). CAS tickles this bug because * Jetty's encodeRedirectURL() is adding jsessionid on redirect after validation, * if it wasn't in a cookie on the request. However, apparently Jetty also puts it in a cookie * on the redirect response, and Firefox accepts it. This is a work-around to redirect that jsessionid * off the URL, since the cookie is enough, and the whole point of CAS redirect after validation is * to get a clean URL anyway (for bookmarks or restored browser tabs). * Other servlet containers and browser combinations may behave differently. * <p/> * This work-around does not attempt to make Hudson work in Jetty without cookies. * A potential approach for that would be for this filter to install an HttpServletRequestWrapper * that cleans jsessionid out of getRequestURI(). However, Hudson would also need to rewrite * all its URLs with the jsessionid, and I have no idea whether it does that. That is an issue * between Hudson and Jetty, and we can just use cookies anyway. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getRequestURI().contains(";jsessionid=") && httpRequest.isRequestedSessionIdFromCookie()) { // without (i.e., with relative) protocol, host, and port String decodedCleanedUrl = URL_PATH_HELPER.getRequestUri(httpRequest); if (StringUtils.isNotBlank(httpRequest.getQueryString())) { decodedCleanedUrl += "?" + URL_PATH_HELPER.decodeRequestString(httpRequest, httpRequest.getQueryString()); } HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect(httpResponse.encodeRedirectURL(decodedCleanedUrl)); return; } } filterChain.doFilter(request, response); } }; // todo: Exclude paths in Hudson#getTarget() from CAS filtering/Authorization? // todo: Add SecurityFilters.commonProviders? // todo: Or, is all that just to support on-demand authentication (upgrade)? return new ChainedServletFilter(authenticationFilter, validationFilter, casToAcegiContext, jettyJsessionidRedirect); }
From source file:pivotal.au.se.gemfirexdweb.controller.CreateHDFSStoreController.java
@RequestMapping(value = "/createhdfsstore", method = RequestMethod.POST) public String createHDFSStoreAction(@ModelAttribute("hdfsStoreAttribute") NewHDFSStore hdfsStoreAttribute, Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception { if (session.getAttribute("user_key") == null) { logger.debug("user_key is null new Login required"); response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } else {/*from w w w . j av a2s .c o m*/ Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key")); if (conn == null) { response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } else { if (conn.isClosed()) { response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } } } logger.debug("Received request to action an event for create HDFS Store"); String storeName = hdfsStoreAttribute.getStoreName(); String nameNode = hdfsStoreAttribute.getNameNode(); String homeDir = hdfsStoreAttribute.getHomeDir(); logger.debug("New HDFS Store Name = " + storeName); // perform some action here with what we have String submit = request.getParameter("pSubmit"); if (submit != null) { // build create HDFS Store SQL StringBuffer createHDFSStore = new StringBuffer(); createHDFSStore.append("create HDFSSTORE " + storeName + " \n"); createHDFSStore.append("NAMENODE '" + nameNode + "' \n"); createHDFSStore.append("HOMEDIR '" + homeDir + "' \n"); if (!checkIfParameterEmpty(request, "batchSize")) { createHDFSStore.append("BatchSize " + hdfsStoreAttribute.getBatchSize() + " \n"); } if (!checkIfParameterEmpty(request, "batchTimeInterval")) { createHDFSStore.append("BatchTimeInterval " + hdfsStoreAttribute.getBatchTimeInterval() + " \n"); } if (!checkIfParameterEmpty(request, "maxQueueMemory")) { createHDFSStore.append("MaxQueueMemory " + hdfsStoreAttribute.getMaxQueueMemory() + " \n"); } if (!checkIfParameterEmpty(request, "minorCompact")) { createHDFSStore.append("MinorCompact " + hdfsStoreAttribute.getMinorCompact() + " \n"); } if (!checkIfParameterEmpty(request, "maxInputFileSize")) { createHDFSStore.append("MaxInputFileSize " + hdfsStoreAttribute.getMaxInputFileSize() + " \n"); } if (!checkIfParameterEmpty(request, "minInputFileCount")) { createHDFSStore.append("MinInputFileCount " + hdfsStoreAttribute.getMinInputFileCount() + " \n"); } if (!checkIfParameterEmpty(request, "maxInputFileCount")) { createHDFSStore.append("MaxInputFileCount " + hdfsStoreAttribute.getMaxInputFileCount() + " \n"); } if (!checkIfParameterEmpty(request, "minorCompactionThreads")) { createHDFSStore .append("MinorCompactionThreads " + hdfsStoreAttribute.getMinorCompactionThreads() + " \n"); } if (!checkIfParameterEmpty(request, "majorCompact")) { createHDFSStore.append("MajorCompact " + hdfsStoreAttribute.getMajorCompact() + " \n"); } if (!checkIfParameterEmpty(request, "majorCompactionInterval")) { createHDFSStore.append( "MajorCompactionInterval " + hdfsStoreAttribute.getMajorCompactionInterval() + " \n"); } if (!checkIfParameterEmpty(request, "majorCompactionThreads")) { createHDFSStore .append("MajorCompactionThreads " + hdfsStoreAttribute.getMajorCompactionThreads() + " \n"); } if (!checkIfParameterEmpty(request, "maxWriteOnlyFileSize")) { createHDFSStore .append("MaxWriteOnlyFileSize " + hdfsStoreAttribute.getMaxWriteOnlyFileSize() + " \n"); } if (!checkIfParameterEmpty(request, "writeOnlyRolloverInterval")) { createHDFSStore.append("WriteOnlyFileRolloverInterval " + hdfsStoreAttribute.getWriteOnlyRolloverInterval() + " \n"); } if (!checkIfParameterEmpty(request, "additionalParams")) { createHDFSStore.append(hdfsStoreAttribute.getAdditionalParams()); } if (submit.equalsIgnoreCase("create")) { Result result = new Result(); logger.debug("Creating hdfs store as -> " + createHDFSStore.toString()); result = GemFireXDWebDAOUtil.runCommand(createHDFSStore.toString(), (String) session.getAttribute("user_key")); model.addAttribute("result", result); } else if (submit.equalsIgnoreCase("Show SQL")) { logger.debug("Create HDFS Store SQL as follows as -> " + createHDFSStore.toString()); model.addAttribute("sql", createHDFSStore.toString()); } else if (submit.equalsIgnoreCase("Save to File")) { response.setContentType(SAVE_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=" + String.format(FILENAME, storeName)); ServletOutputStream out = response.getOutputStream(); out.println(createHDFSStore.toString()); out.close(); return null; } } // This will resolve to /WEB-INF/jsp/create-table.jsp return "create-hdfsstore"; }
From source file:com.chessoft.filter.AuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(false); String uri = httpRequest.getRequestURI(); if (StringUtils.contains(uri, "/login.xhtml") || (session != null && session.getAttribute("login") != null) || StringUtils.contains(uri, "javax.faces.resource") || StringUtils.contains(uri, "org/apache/myfaces/tobago/renderkit")) { chain.doFilter(request, response); } else {//from w ww .j a v a 2 s.c o m httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.xhtml"); } }
From source file:com.ssic.education.government.controller.EduSchoolController.java
public EduUsersDto getLoginUser(HttpServletRequest request, HttpServletResponse response, HttpSession session, String id) {// w ww. j a v a2s .c om if (id == null) { try { response.sendRedirect(request.getContextPath() + "/login.htm"); return null; } catch (IOException e) { e.printStackTrace(); } } EduUsersDto usersDto = new EduUsersDto(); usersDto.setId(id); return eduUsersService.getUserInfo(usersDto); }
From source file:pivotal.au.se.gemfirexdweb.controller.CreateIndexController.java
@RequestMapping(value = "/createindex", method = RequestMethod.POST) public String createIndexAction(@ModelAttribute("indexAttribute") NewIndex indexAttribute, Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception { if (session.getAttribute("user_key") == null) { logger.debug("user_key is null new Login required"); response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } else {//ww w .ja va 2s . c o m Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key")); if (conn == null) { response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } else { if (conn.isClosed()) { response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } } } logger.debug("Received request to action an event for create index"); String tabName = indexAttribute.getTableName(); String schema = indexAttribute.getSchemaName(); String unique = indexAttribute.getUnique(); String idxName = indexAttribute.getIndexName(); String submit = request.getParameter("pSubmit"); String[] selectedColumns = request.getParameterValues("selected_column[]"); String[] indexOrder = request.getParameterValues("idxOrder[]"); String[] position = request.getParameterValues("position[]"); logger.debug("selectedColumns = " + Arrays.toString(selectedColumns)); logger.debug("indexOrder = " + Arrays.toString(indexOrder)); logger.debug("position = " + Arrays.toString(position)); IndexDAO indexDAO = GemFireXDWebDAOFactory.getIndexDAO(); List<IndexColumn> columns = indexDAO.retrieveIndexColumns(schema, tabName, (String) session.getAttribute("user_key")); StringBuffer createIndex = new StringBuffer(); if (unique.equalsIgnoreCase("Y")) { createIndex.append("create unique index " + idxName + " on " + schema + "." + tabName + " "); } else { createIndex.append("create index " + idxName + " on " + schema + "." + tabName + " "); } createIndex.append("("); if (selectedColumns != null) { int i = 0; Map<String, IndexDefinition> cols = new HashMap<String, IndexDefinition>(); for (String column : selectedColumns) { String columnName = column.substring(0, column.indexOf("_")); String index = column.substring(column.indexOf("_") + 1); String pos = position[Integer.parseInt(index) - 1]; if (pos.trim().length() == 0) { pos = "" + i; } logger.debug("Column = " + columnName + ", indexOrder = " + indexOrder[Integer.parseInt(index) - 1] + ", position = " + pos); IndexDefinition idxDef = new IndexDefinition(columnName, indexOrder[Integer.parseInt(index) - 1]); cols.put("" + pos, idxDef); i++; } // sort map and create index now SortedSet<String> keys = new TreeSet<String>(cols.keySet()); int length = keys.size(); i = 0; for (String key : keys) { IndexDefinition idxDefTemp = cols.get(key); if (i == (length - 1)) { createIndex.append(idxDefTemp.getColumnName() + " " + idxDefTemp.getOrderType() + ")"); } else { createIndex.append(idxDefTemp.getColumnName() + " " + idxDefTemp.getOrderType() + ", "); } i++; } } if (!checkIfParameterEmpty(request, "caseSensitive")) { createIndex.append(" " + request.getParameter("caseSensitive") + "\n"); } if (submit.equalsIgnoreCase("create")) { Result result = new Result(); logger.debug("Creating index as -> " + createIndex.toString()); result = GemFireXDWebDAOUtil.runCommand(createIndex.toString(), (String) session.getAttribute("user_key")); model.addAttribute("result", result); model.addAttribute("tabName", tabName); model.addAttribute("tableSchemaName", schema); model.addAttribute("columns", columns); model.addAttribute("schema", schema); session.removeAttribute("numColumns"); } else if (submit.equalsIgnoreCase("Show SQL")) { logger.debug("Index SQL as follows as -> " + createIndex.toString()); model.addAttribute("sql", createIndex.toString()); model.addAttribute("tabName", tabName); model.addAttribute("tableSchemaName", schema); model.addAttribute("columns", columns); model.addAttribute("schema", schema); } else if (submit.equalsIgnoreCase("Save to File")) { response.setContentType(SAVE_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=" + String.format(FILENAME, idxName)); ServletOutputStream out = response.getOutputStream(); out.println(createIndex.toString()); out.close(); return null; } // This will resolve to /WEB-INF/jsp/create-index.jsp return "create-index"; }
From source file:com.ci6225.marketzone.servlet.seller.ViewProductDetailServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//www . j av a 2 s . com */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int productId = Integer.parseInt(request.getParameter("productId")); Product product = productBean.getProduct(productId); request.setAttribute("product", product); RequestDispatcher rd = request.getRequestDispatcher("./jsp/seller/update_product.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); response.sendRedirect("./"); } }