Java Code Examples for javax.servlet.http.HttpServletResponse#encodeRedirectURL()

The following examples show how to use javax.servlet.http.HttpServletResponse#encodeRedirectURL() . These examples are extracted from open source projects. 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 Project: journaldev   File: LoginServlet.java    License: MIT License 6 votes vote down vote up
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 2
Source Project: nano-framework   File: ForwardView.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: nano-framework   File: RedirectView.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: webcurator   File: ReportSaveController.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: smart-home-java   File: FakeAuthServlet.java    License: Apache License 2.0 5 votes vote down vote up
@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 6
/**
 * 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 7
Source Project: hadoop   File: ProxyUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 8
Source Project: big-c   File: ProxyUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 9
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 10
Source Project: wallride   File: ControllerUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 11
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 12
public String encodeRedirectURLRewrite(HttpServletResponse resp, String url) {
    return resp.encodeRedirectURL(url);
}
 
Example 13
Source Project: scipio-erp   File: SimpleRedirectFilter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @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 14
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 15
/**
 * 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 16
/**
 * 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 17
@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 18
@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 19
@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 Project: scipio-erp   File: ContextFilter.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}