Java Code Examples for javax.servlet.http.HttpServletResponse#encodeRedirectURL()
The following examples show how to use
javax.servlet.http.HttpServletResponse#encodeRedirectURL() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReportSaveController.java From webcurator with Apache License 2.0 | 6 votes |
@Override protected ModelAndView processFormSubmission(HttpServletRequest req, HttpServletResponse resp, Object comm, BindException exc) throws Exception { ReportSaveCommand com = (ReportSaveCommand) comm; String format = com.getFormat(); String action = com.getActionCmd(); String dest = resp.encodeRedirectURL(req.getContextPath() + "/curator/report/report.html"); if(action != null && action.equals(ACTION_SAVE)){ OperationalReport operationalReport = (OperationalReport) req.getSession().getAttribute("operationalReport"); operationalReport.getDownloadRendering(req, resp, "report", format, dest); } else if(action != null && action.equals(ACTION_CANCEL)){ resp.sendRedirect(dest); } else { log.warn("action=[" + (action == null ? "null" : action) + "]"); } return null; }
Example 2
Source File: RedirectView.java From nano-framework with Apache License 2.0 | 6 votes |
@Override public void redirect(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (response == null || request == null) { return; } StringBuilder builder = new StringBuilder(); if (model != null && model.size() > 0) { if(!page.contains("?")) { builder.append('?'); } else { builder.append('&'); } builder.append("__version=").append(System.currentTimeMillis()); model.forEach((name, o) -> builder.append('&').append(name).append('=').append(toJSONString(o))); } String encodedRedirectURL = response.encodeRedirectURL(page + builder.toString()); /** HttpServletResponse.sendRedirect */ response.sendRedirect(encodedRedirectURL); }
Example 3
Source File: ForwardView.java From nano-framework with Apache License 2.0 | 6 votes |
@Override public void redirect(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if(response == null || request == null) return ; if(model != null && model.size() > 0) { model.forEach((name, o) -> request.setAttribute(name, o)); } String encodedRedirectURL = response.encodeRedirectURL(page); // if(encodedRedirectURL.contains("/WEB-INF")) { request.getRequestDispatcher(encodedRedirectURL).forward(request, response); // } else { // String root; // if(!encodedRedirectURL.startsWith(root = System.getProperty(Constants.CONTEXT_ROOT))) // encodedRedirectURL = root + encodedRedirectURL; // // response.sendRedirect(encodedRedirectURL); // // } }
Example 4
Source File: LoginServlet.java From journaldev with MIT License | 6 votes |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get request parameters for userID and password String user = request.getParameter("user"); String pwd = request.getParameter("pwd"); if(userID.equals(user) && password.equals(pwd)){ HttpSession session = request.getSession(); session.setAttribute("user", "Pankaj"); //setting session to expiry in 30 mins session.setMaxInactiveInterval(30*60); Cookie userName = new Cookie("user", user); response.addCookie(userName); String encodedURL = response.encodeRedirectURL("LoginSuccess.jsp"); response.sendRedirect(encodedURL); }else{ RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html"); PrintWriter out= response.getWriter(); out.println("<font color=red>Either user name or password is wrong.</font>"); rd.include(request, response); } }
Example 5
Source File: AbstractWidgetExecutorService.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
protected static String extractJspOutput(RequestContext reqCtx, String jspPath) throws ServletException, IOException { HttpServletRequest request = reqCtx.getRequest(); HttpServletResponse response = reqCtx.getResponse(); BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(response); ServletContext context = request.getSession().getServletContext(); String url = response.encodeRedirectURL(jspPath); RequestDispatcher dispatcher = context.getRequestDispatcher(url); dispatcher.include(request, wrapper); return wrapper.getOutput(); }
Example 6
Source File: FakeAuthServlet.java From smart-home-java with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { String redirectURL = String.format( "%s?code=%s&state=%s", URLDecoder.decode(req.getParameter("redirect_uri"), "UTF8"), "xxxxxx", req.getParameter("state")); String loginUrl = res.encodeRedirectURL("/login?responseurl=" + redirectURL); res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); res.setHeader("Location", loginUrl); res.getWriter().flush(); }
Example 7
Source File: ControllerUtils.java From wallride with Apache License 2.0 | 5 votes |
public static ResponseEntity<?> createRedirectResponseEntity( HttpServletRequest nativeRequest, HttpServletResponse nativeResponse, String path) { UrlPathHelper pathHelper = new UrlPathHelper(); String url = pathHelper.getContextPath(nativeRequest) + path; String encodedUrl = nativeResponse.encodeRedirectURL(url); HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create(encodedUrl)); ResponseEntity<?> response = new ResponseEntity<>(null, headers, HttpStatus.FOUND); return response; }
Example 8
Source File: SimpleResponseManager.java From lastaflute with Apache License 2.0 | 5 votes |
protected String buildRedirectUrl(HttpServletResponse response, Redirectable redirectable) { final String routingPath = redirectable.getRoutingPath(); final String redirectUrl; if (needsContextPathForRedirectPath(routingPath, redirectable.isAsIs())) { redirectUrl = getRequestManager().getContextPath() + routingPath; } else { redirectUrl = routingPath; } return response.encodeRedirectURL(redirectUrl); }
Example 9
Source File: ProxyUtils.java From big-c with Apache License 2.0 | 5 votes |
/** * Handle redirects with a status code that can in future support verbs other * than GET, thus supporting full REST functionality. * <p> * The target URL is included in the redirect text returned * <p> * At the end of this method, the output stream is closed. * * @param request request (hence: the verb and any other information * relevant to a redirect) * @param response the response * @param target the target URL -unencoded * */ public static void sendRedirect(HttpServletRequest request, HttpServletResponse response, String target) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Redirecting {} {} to {}", request.getMethod(), request.getRequestURI(), target); } String location = response.encodeRedirectURL(target); response.setStatus(HttpServletResponse.SC_FOUND); response.setHeader(LOCATION, location); response.setContentType(MimeType.HTML); PrintWriter writer = response.getWriter(); Page p = new Page(writer); p.html() .head().title("Moved")._() .body() .h1("Moved") .div() ._("Content has moved ") .a(location, "here")._() ._()._(); writer.close(); }
Example 10
Source File: ProxyUtils.java From hadoop with Apache License 2.0 | 5 votes |
/** * Handle redirects with a status code that can in future support verbs other * than GET, thus supporting full REST functionality. * <p> * The target URL is included in the redirect text returned * <p> * At the end of this method, the output stream is closed. * * @param request request (hence: the verb and any other information * relevant to a redirect) * @param response the response * @param target the target URL -unencoded * */ public static void sendRedirect(HttpServletRequest request, HttpServletResponse response, String target) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Redirecting {} {} to {}", request.getMethod(), request.getRequestURI(), target); } String location = response.encodeRedirectURL(target); response.setStatus(HttpServletResponse.SC_FOUND); response.setHeader(LOCATION, location); response.setContentType(MimeType.HTML); PrintWriter writer = response.getWriter(); Page p = new Page(writer); p.html() .head().title("Moved")._() .body() .h1("Moved") .div() ._("Content has moved ") .a(location, "here")._() ._()._(); writer.close(); }
Example 11
Source File: Oauth2LogoutHandler.java From ods-provisioning-app with Apache License 2.0 | 5 votes |
/** * Builds the uri that is used from the identity manager to redirect the call after the logout url * was called from the provision app * * @param httpServletRequest servlet request * @param httpServletResponse servlet response * @return the redirect uri */ private String buildRedirectUri( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { StringBuilder url = new StringBuilder(); url.append(httpServletRequest.getScheme()) .append("://") .append(httpServletRequest.getServerName()); final int serverPort = httpServletRequest.getServerPort(); if (serverPort != 80 && serverPort != 443) { url.append(":").append(serverPort); } url.append(httpServletRequest.getContextPath()).append("/login"); return httpServletResponse.encodeRedirectURL(url.toString()); }
Example 12
Source File: PortletContainerImpl.java From portals-pluto with Apache License 2.0 | 4 votes |
/** * Process action for the portlet associated with the given portlet window. * @param portletWindow the portlet window. * @param request the servlet request. * @param response the servlet response. * @param isRedirect Flag indicating whether redirect is to be performed. * should be true for Action request and false for Ajax Action or * Partial Action requests. * @throws PortletException * @throws IOException * @throws PortletContainerException * * @see javax.portlet.Portlet#processAction(ActionRequest, ActionResponse) */ public void doAction(PortletWindow portletWindow, HttpServletRequest request, HttpServletResponse response, boolean isRedirect) throws PortletException, IOException, PortletContainerException { ensureInitialized(); debugWithName("Action request received for portlet: " + portletWindow.getPortletDefinition().getPortletName()); PortletRequestContextService rcService = getContainerServices().getPortletRequestContextService(); PortletEnvironmentService envService = getContainerServices().getPortletEnvironmentService(); PortletInvokerService invoker = getContainerServices().getPortletInvokerService(); PortletRequestContext requestContext = rcService.getPortletActionRequestContext(this, request, response, portletWindow); PortletActionResponseContext responseContext = rcService.getPortletActionResponseContext(this, request, response, portletWindow, requestContext); responseContext.setPropsAllowed(true); ActionRequest portletRequest = envService.createActionRequest(requestContext, responseContext); ActionResponse portletResponse = envService.createActionResponse(responseContext); FilterManager filterManager = filterInitialisation(portletWindow,PortletRequest.ACTION_PHASE); String location = null; String logtxt = "Portlet action"; if (!isRedirect) { logtxt = "Portlet Ajax or Partial action"; } try { invoker.action(requestContext, portletRequest, portletResponse, filterManager); debugWithName(logtxt + " processed for: " + portletWindow.getPortletDefinition().getPortletName()); // add http headers to response responseContext.processHttpHeaders(); // Mark portlet interaction is completed: backend implementation can flush response state now responseContext.close(); if (!responseContext.isRedirect()) { List<Event> events = responseContext.getEvents(); if (!events.isEmpty()) { getContainerServices().getEventCoordinationService().processEvents(this, portletWindow, request, response, events); } } } catch (Throwable t) { // Throw away events and parameters that were set responseContext.reset(); // just swallow the exception, ignoring changes to the response StringBuilder txt = new StringBuilder(128); txt.append("Exception during action request processing. Exception: "); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); txt.append(sw.toString()); LOG.warn(txt.toString()); } finally { // After processing action and possible event handling, retrieve the target response URL to be redirected to // This can either be a renderURL or an external URL (optionally containing a future renderURL as query parameter location = response.encodeRedirectURL(responseContext.getResponseURL()); responseContext.release(); } if (isRedirect) { redirect(request, response, location); } debugWithName(logtxt + " done for: " + portletWindow.getPortletDefinition().getPortletName()); }
Example 13
Source File: MCRTileCombineServlet.java From mycore with GNU General Public License v3.0 | 4 votes |
/** * prepares render process and gets IView2 file and combines tiles. * The image dimensions and path are determined from {@link HttpServletRequest#getPathInfo()}: * <code>/{zoomAlias}/{derivateID}/{absoluteImagePath}</code> * where <code>zoomAlias</code> is mapped like this: * <table> * <caption>Mapping of zoomAlias to actual zoom level</caption> * <tr><th>zoomAlias</th><th>zoom level</th></tr> * <tr><td>'MIN'</td><td>1</td></tr> * <tr><td>'MID'</td><td>2</td></tr> * <tr><td>'MAX'</td><td>3</td></tr> * <tr><td>default and all others</td><td>0</td></tr> * </table> * * See {@link #init()} how to attach a footer to every generated image. */ @Override protected void think(final MCRServletJob job) throws IOException, JDOMException { final HttpServletRequest request = job.getRequest(); try { String pathInfo = request.getPathInfo(); if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } String zoomAlias = pathInfo.substring(0, pathInfo.indexOf('/')); pathInfo = pathInfo.substring(zoomAlias.length() + 1); final String derivate = pathInfo.substring(0, pathInfo.indexOf('/')); String imagePath = pathInfo.substring(derivate.length()); LOGGER.info("Zoom-Level: {}, derivate: {}, image: {}", zoomAlias, derivate, imagePath); final Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivate, imagePath); try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) { Path iviewFileRoot = fs.getRootDirectories().iterator().next(); final MCRTiledPictureProps pictureProps = MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot); final int maxZoomLevel = pictureProps.getZoomlevel(); request.setAttribute(THUMBNAIL_KEY, iviewFile); LOGGER.info("IView2 file: {}", iviewFile); int zoomLevel = 0; switch (zoomAlias) { case "MIN": zoomLevel = 1; break; case "MID": zoomLevel = 2; break; case "MAX": zoomLevel = 3; break; } HttpServletResponse response = job.getResponse(); if (zoomLevel > maxZoomLevel) { switch (maxZoomLevel) { case 2: zoomAlias = "MID"; break; case 1: zoomAlias = "MIN"; break; default: zoomAlias = "THUMB"; break; } if (!imagePath.startsWith("/")) { imagePath = "/" + imagePath; } String redirectURL = response.encodeRedirectURL(new MessageFormat("{0}{1}/{2}/{3}{4}", Locale.ROOT) .format(new Object[] { request.getContextPath(), request.getServletPath(), zoomAlias, derivate, imagePath })); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", redirectURL); response.flushBuffer(); return; } if (zoomLevel == 0 && footerImpl == null) { //we're done, sendThumbnail is called in render phase return; } ImageReader reader = MCRIView2Tools.getTileImageReader(); try { BufferedImage combinedImage = MCRIView2Tools.getZoomLevel(iviewFileRoot, pictureProps, reader, zoomLevel); if (combinedImage != null) { if (footerImpl != null) { BufferedImage footer = footerImpl.getFooter(combinedImage.getWidth(), derivate, imagePath); combinedImage = attachFooter(combinedImage, footer); } request.setAttribute(IMAGE_KEY, combinedImage); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { reader.dispose(); } } } finally { LOGGER.info("Finished sending {}", request.getPathInfo()); } }
Example 14
Source File: IndexController.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
@RequestMapping( value = "/api", method = RequestMethod.GET ) public void getIndex( HttpServletRequest request, HttpServletResponse response ) throws IOException { String location = response.encodeRedirectURL( "/resources" ); response.sendRedirect( ContextUtils.getRootPath( request ) + location ); }
Example 15
Source File: IndexController.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
@RequestMapping( value = "/", method = RequestMethod.GET ) public void getIndexWithSlash( HttpServletRequest request, HttpServletResponse response ) throws IOException { String location = response.encodeRedirectURL( "/resources" ); response.sendRedirect( ContextUtils.getRootPath( request ) + location ); }
Example 16
Source File: BuildManifest.java From weasis-pacs-connector with Eclipse Public License 2.0 | 4 votes |
private void buildManifest(HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_ACCEPTED); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1 response.setHeader("Pragma", "no-cache"); // HTTP 1.0 response.setDateHeader("Expires", -1); // Proxies try { if (LOGGER.isDebugEnabled()) { ServletUtil.logInfo(request, LOGGER); } ConnectorProperties connectorProperties = (ConnectorProperties) this.getServletContext().getAttribute("componentProperties"); // Check if the source of this request is allowed if (!ServletUtil.isRequestAllowed(request, connectorProperties, LOGGER)) { return; } ConnectorProperties props = connectorProperties.getResolveConnectorProperties(request); boolean gzip = request.getParameter("gzip") != null; ManifestBuilder builder = ServletUtil.buildManifest(request, props); // BUILDER IS NULL WHEN NO ALLOWED PARAMETER ARE GIVEN WHICH LEADS TO NO MANIFEST BUILT if (builder == null) { // NO body in response, see: https://httpstatuses.com/204 response.setStatus(HttpServletResponse.SC_NO_CONTENT); response.setHeader("Cause", "No allowed parameters have been given to build a manifest"); } else { String wadoQueryUrl = ServletUtil.buildManifestURL(request, builder, props, gzip); wadoQueryUrl = response.encodeRedirectURL(wadoQueryUrl); response.setStatus(HttpServletResponse.SC_OK); if (request.getParameter(ConnectorProperties.PARAM_URL) != null) { response.setContentType("text/plain"); response.getWriter().print(wadoQueryUrl); } else { response.sendRedirect(wadoQueryUrl); } } } catch (Exception e) { LOGGER.error("Building manifest", e); ServletUtil.sendResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
Example 17
Source File: SimpleRedirectFilter.java From scipio-erp with Apache License 2.0 | 4 votes |
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (matchPattern != null && replacement != null) { String matchPath; // FIXME: These values are all still URL-encoded! if (matchFullPath) { matchPath = httpRequest.getRequestURI(); if (httpRequest.getQueryString() != null) { matchPath += "?" + httpRequest.getQueryString(); } } else { matchPath = httpRequest.getContextPath(); } Matcher m = matchPattern.matcher(matchPath); if (m.find()) { StringBuffer fullTargetSb = getFullHost(httpRequest); m.appendReplacement(fullTargetSb, replacement); m.appendTail(fullTargetSb); if (!matchFullPath) { fullTargetSb.append(getFullPostContextPath(httpRequest).toString()); } // SCIPIO: NOTE: It's possible this should be encodeURL + strip jsessionid instead (even if redirect)... String fullTarget = httpResponse.encodeRedirectURL(fullTargetSb.toString()); if (usePermanentRedirect) { httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); httpResponse.setHeader("Location", fullTarget); return; } else { httpResponse.sendRedirect(fullTarget); return; } } } // we're done checking; continue on chain.doFilter(request, response); }
Example 18
Source File: UrlRewriting.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 4 votes |
public String encodeRedirectURLRewrite(HttpServletResponse resp, String url) { return resp.encodeRedirectURL(url); }
Example 19
Source File: FIDOAuthenticator.java From carbon-identity with Apache License 2.0 | 4 votes |
@Override protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { //FIDO BE service component U2FService u2FService = U2FService.getInstance(); try { //authentication page's URL. String loginPage; loginPage = context.getAuthenticatorProperties().get(IdentityApplicationConstants.Authenticator.FIDO .FIDO_AUTH); if (StringUtils.isBlank(loginPage)){ loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL().replace("login.do", "fido-auth.jsp"); } //username from basic authenticator. AuthenticatedUser user = getUsername(context); //origin as appID eg.: http://example.com:8080 String appID = FIDOUtil.getOrigin(request); //calls BE service method to generate challenge. FIDOUser fidoUser = new FIDOUser(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain(), appID); AuthenticateRequestData data = u2FService.startAuthentication(fidoUser); //redirect to FIDO login page if (data != null) { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?")) + "&authenticators=" + getName() + ":" + "LOCAL" + "&type=fido&sessionDataKey=" + request.getParameter("sessionDataKey") + "&data=" + data.toJson()); } else { String redirectURL = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL(); redirectURL = response.encodeRedirectURL(redirectURL + ("?")) + "&failedUsername=" + URLEncoder.encode(user.getUserName(), IdentityCoreConstants.UTF_8) + "&statusMsg=" + URLEncoder.encode(FIDOAuthenticatorConstants.AUTHENTICATION_ERROR_MESSAGE, IdentityCoreConstants.UTF_8) + "&status=" + URLEncoder.encode(FIDOAuthenticatorConstants.AUTHENTICATION_STATUS, IdentityCoreConstants.UTF_8); response.sendRedirect(redirectURL); } } catch (IOException e) { throw new AuthenticationFailedException( "Could not initiate FIDO authentication request", e); } }
Example 20
Source File: ContextFilter.java From scipio-erp with Apache License 2.0 | 2 votes |
/** * SCIPIO: local redirect URL encode method for ContextFilter redirects (only). * TODO: REVIEW: method used * Added 2017-11-03. */ protected String encodeRedirectURL(HttpServletResponse response, String url) { // SCIPIO: TODO: REVIEW: It's possible this should be encodeURL + strip jsessionid instead (even if redirect)... return response.encodeRedirectURL(url); }