Java Code Examples for javax.servlet.ServletRequest#getRequestDispatcher()

The following examples show how to use javax.servlet.ServletRequest#getRequestDispatcher() . 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: JspRuntimeLibrary.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Perform a RequestDispatcher.include() operation, with optional flushing
 * of the response beforehand.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param relativePath The relative path of the resource to be included
 * @param out The Writer to whom we are currently writing
 * @param flush Should we flush before the include is processed?
 *
 * @exception IOException if thrown by the included servlet
 * @exception ServletException if thrown by the included servlet
 */
public static void include(ServletRequest request,
                           ServletResponse response,
                           String relativePath,
                           JspWriter out,
                           boolean flush)
    throws IOException, ServletException {

    if (flush && !(out instanceof BodyContent))
        out.flush();

    // FIXME - It is tempting to use request.getRequestDispatcher() to
    // resolve a relative path directly, but Catalina currently does not
    // take into account whether the caller is inside a RequestDispatcher
    // include or not.  Whether Catalina *should* take that into account
    // is a spec issue currently under review.  In the mean time,
    // replicate Jasper's previous behavior

    String resourcePath = getContextRelativePath(request, relativePath);
    RequestDispatcher rd = request.getRequestDispatcher(resourcePath);

    rd.include(request,
               new ServletResponseWrapperInclude(response, out));

}
 
Example 2
Source File: JspRuntimeLibrary.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a RequestDispatcher.include() operation, with optional flushing
 * of the response beforehand.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param relativePath The relative path of the resource to be included
 * @param out The Writer to whom we are currently writing
 * @param flush Should we flush before the include is processed?
 *
 * @exception IOException if thrown by the included servlet
 * @exception ServletException if thrown by the included servlet
 */
public static void include(ServletRequest request,
                           ServletResponse response,
                           String relativePath,
                           JspWriter out,
                           boolean flush)
    throws IOException, ServletException {

    if (flush && !(out instanceof BodyContent))
        out.flush();

    // FIXME - It is tempting to use request.getRequestDispatcher() to
    // resolve a relative path directly, but Catalina currently does not
    // take into account whether the caller is inside a RequestDispatcher
    // include or not.  Whether Catalina *should* take that into account
    // is a spec issue currently under review.  In the mean time,
    // replicate Jasper's previous behavior

    String resourcePath = getContextRelativePath(request, relativePath);
    RequestDispatcher rd = request.getRequestDispatcher(resourcePath);

    rd.include(request,
               new ServletResponseWrapperInclude(response, out));

}
 
Example 3
Source File: JspRuntimeLibrary.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a RequestDispatcher.include() operation, with optional flushing
 * of the response beforehand.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param relativePath The relative path of the resource to be included
 * @param out The Writer to whom we are currently writing
 * @param flush Should we flush before the include is processed?
 *
 * @exception IOException if thrown by the included servlet
 * @exception ServletException if thrown by the included servlet
 */
public static void include(ServletRequest request,
                           ServletResponse response,
                           String relativePath,
                           JspWriter out,
                           boolean flush)
    throws IOException, ServletException {

    if (flush && !(out instanceof BodyContent))
        out.flush();

    // FIXME - It is tempting to use request.getRequestDispatcher() to
    // resolve a relative path directly, but Catalina currently does not
    // take into account whether the caller is inside a RequestDispatcher
    // include or not.  Whether Catalina *should* take that into account
    // is a spec issue currently under review.  In the mean time,
    // replicate Jasper's previous behavior

    String resourcePath = getContextRelativePath(request, relativePath);
    RequestDispatcher rd = request.getRequestDispatcher(resourcePath);

    rd.include(request,
               new ServletResponseWrapperInclude(response, out));

}
 
Example 4
Source File: JspRuntimeLibrary.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Perform a RequestDispatcher.include() operation, with optional flushing
 * of the response beforehand.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param relativePath The relative path of the resource to be included
 * @param out The Writer to whom we are currently writing
 * @param flush Should we flush before the include is processed?
 *
 * @exception IOException if thrown by the included servlet
 * @exception ServletException if thrown by the included servlet
 */
public static void include(ServletRequest request,
                           ServletResponse response,
                           String relativePath,
                           JspWriter out,
                           boolean flush)
    throws IOException, ServletException {

    if (flush && !(out instanceof BodyContent))
        out.flush();

    // FIXME - It is tempting to use request.getRequestDispatcher() to
    // resolve a relative path directly, but Catalina currently does not
    // take into account whether the caller is inside a RequestDispatcher
    // include or not.  Whether Catalina *should* take that into account
    // is a spec issue currently under review.  In the mean time,
    // replicate Jasper's previous behavior

    String resourcePath = getContextRelativePath(request, relativePath);
    RequestDispatcher rd = request.getRequestDispatcher(resourcePath);

    rd.include(request,
               new ServletResponseWrapperInclude(response, out));

}
 
Example 5
Source File: BirtInterceptingFilter.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
private void forwardToErrorPage(ServletRequest request, ServletResponse response) throws ServletException, IOException {
	request.setAttribute("error", new Exception("Not authenticated"));
	RequestDispatcher dispatcher = request.getRequestDispatcher(getConfigService().getValue(ConfigValue.BirtErrorPage));
	dispatcher.forward(request, response);
}
 
Example 6
Source File: BirtNoDocumentParameterInterceptor.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
private void error(ServletRequest request, ServletResponse response) throws ServletException, IOException {
      request.setAttribute("error", new Exception("Using __document parameter is denied"));
RequestDispatcher dispatcher = request.getRequestDispatcher(getConfigService().getValue(ConfigValue.BirtErrorPage));
      dispatcher.forward(request, response);
  }
 
Example 7
Source File: ContentUrlFilter.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Delegator delegator = (Delegator) httpRequest.getServletContext().getAttribute("delegator"); // SCIPIO: NOTE: no longer need getSession() for getServletContext(), since servlet API 3.0

    //Get ServletContext
    ServletContext servletContext = config.getServletContext();

    ContextFilter.setCharacterEncoding(request);

    //Set request attribute and session
    UrlServletHelper.setRequestAttributes(request, delegator, servletContext);
    String urlContentId = null;
    // SCIPIO: 2018-07-30: stock bugfix: prevents having URL parameters
    //String pathInfo = UtilHttp.getFullRequestUrl(httpRequest);
    String pathInfo = httpRequest.getServletPath(); // SCIPIO: NOTE: getServletPath() is what CatalogUrlFilter did, and known to work
    if (UtilValidate.isNotEmpty(pathInfo)) {
        String alternativeUrl = pathInfo.substring(pathInfo.lastIndexOf("/"));
        if (alternativeUrl.endsWith(urlSuffix)) { // SCIPIO: unhardcode view request
            // SCIPIO: strip alt URL suffix
            alternativeUrl = alternativeUrl.substring(0, alternativeUrl.length() - urlSuffix.length());
            try {
                GenericValue contentDataResourceView = EntityQuery.use(delegator).from("ContentDataResourceView")
                        .where("drObjectInfo", alternativeUrl)
                        .orderBy("createdDate DESC").queryFirst();
                if (contentDataResourceView != null) {
                    GenericValue content = EntityQuery.use(delegator).from("ContentAssoc")
                            .where("contentAssocTypeId", "ALTERNATIVE_URL",
                                    "contentIdTo", contentDataResourceView.get("contentId"))
                            .filterByDate().queryFirst();
                    if (content != null) {
                        urlContentId = content.getString("contentId");
                    }
                }
            } catch (Exception e) {
                Debug.logWarning(e.getMessage(), module);
            }
        }
        if (UtilValidate.isNotEmpty(urlContentId)) {
            StringBuilder urlBuilder = new StringBuilder();
            urlBuilder.append(RequestHandler.getControlServletPath(request)); // SCIPIO
            urlBuilder.append("/" + viewRequest + "?contentId=" + urlContentId); // SCIPIO: local var for viewRequest
            // SCIPIO: 2018-07-31: fix lost extra parameters
            // NOTE: this will include the viewIndex, viewSize, etc. parameters that are processed again below,
            // but this is unlikely to cause an issue...
            String queryString = httpRequest.getQueryString();
            if (queryString != null) {
                urlBuilder.append("&");
                urlBuilder.append(queryString);
            }

            ContextFilter.setAttributesFromRequestBody(request);
            //Set view query parameters
            UrlServletHelper.setViewQueryParameters(request, urlBuilder);
            //Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); // SCIPIO: 2018-07-31: makes no sense
            RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString());
            dispatch.forward(request, response);
            return;
        }

        //Check path alias
        UrlServletHelper.checkPathAlias(request, httpResponse, delegator, pathInfo);
    }
    // we're done checking; continue on
    chain.doFilter(request, response);
}
 
Example 8
Source File: IndexFilter.java    From peer-os with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain )
        throws IOException, ServletException
{
    if ( servletRequest instanceof HttpServletRequest )
    {
        String url = ( ( HttpServletRequest ) servletRequest ).getRequestURI();

        if ( "".equals( url ) || "/".equals( url ) )
        {
            RequestDispatcher view = servletRequest.getRequestDispatcher( "index.html" );
            HttpServletResponse response = ( HttpServletResponse ) servletResponse;
            boolean isCookieSet = isCookieSet( ( HttpServletRequest ) servletRequest,
                    Common.E2E_PLUGIN_USER_KEY_FINGERPRINT_NAME );
            try
            {
                IdentityManager identityManager = ServiceLocator.getServiceOrNull( IdentityManager.class );
                if ( !isCookieSet && identityManager != null )
                {
                    //identityManager.getActiveUser() returns always null here
                    User user = identityManager.getUserByKeyId( identityManager.getPeerOwnerId() );

                    if ( StringUtils.isBlank( user.getFingerprint() ) )
                    {
                        throw new IllegalStateException( "No Peer owner is set yet..." );
                    }

                    setCookie( response, Common.E2E_PLUGIN_USER_KEY_FINGERPRINT_NAME, user.getFingerprint() );
                }
            }
            catch ( Exception ex )
            {
                if ( !isCookieSet )
                {
                    setCookie( response, Common.E2E_PLUGIN_USER_KEY_FINGERPRINT_NAME, "no owner" );
                }
            }

            view.forward( servletRequest, response );

            return;
        }

        if ( !( url.startsWith( "/rest" ) || url.startsWith( "/subutai" ) || url.startsWith( "/fav" ) || url
                .startsWith( "/plugin" ) || url.startsWith( "/assets" ) || url.startsWith( "/css" ) || url
                .startsWith( "/fonts" ) || url.startsWith( "/scripts" ) || url.startsWith( "/login" ) ) && !url
                .contains( "#" ) )
        {
            try
            {
                ( ( HttpServletResponse ) servletResponse ).sendRedirect( "/#" + url );
            }
            catch ( Exception e )
            {
                log.error( "Error redirecting {}", e.getMessage() );
            }
        }
        else
        {
            filterChain.doFilter( servletRequest, servletResponse );
        }
    }
}
 
Example 9
Source File: SearchEngineFriendlyURLFilter.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest httpReq = (HttpServletRequest) req;
	String uri = httpReq.getRequestURI();

	logDebug("filtering uri - " + uri);

	String foundExtension = null;
	int extensionPosition = -1;
	for (int i = 0; i < extensions.length; i++) {
		extensionPosition = uri.indexOf("." + extensions[i]);
		if ( extensionPosition != -1 ){
			foundExtension = extensions[i];
		}
	}
	
	if (foundExtension != null) {
		int servletPathEnd = extensionPosition + foundExtension.length() + 1;
		if (uri.length() != servletPathEnd) {
			logDebug("found extension match - " + foundExtension);

			// The URI contains an extension that the filter is configured to look
			// for and there's
			// path info so update the servletPath and pathInfo in a request
			// wrapper and let BD process it.
			int contextPathLen = httpReq.getContextPath().length();
			if (contextPathLen == 1)
				contextPathLen = 0;
			String servletPath = uri.substring(contextPathLen, servletPathEnd);
			String pathInfo = uri.substring(servletPathEnd);
			ReqWrapper reqW = new ReqWrapper(httpReq, servletPath, pathInfo);
			RequestDispatcher rd = req.getRequestDispatcher(servletPath);
			rd.forward(reqW, rsp);
			return;
		}
	}

	// The URI doesn't contain an extension that the filter is configured
	// to look for or there's no path info so process it as it is.
	chain.doFilter(req, rsp);
	return;
}
 
Example 10
Source File: SamlFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    ServletHttpFacade facade = new ServletHttpFacade(request, response);
    SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        response.sendError(403);
        log.fine("deployment not configured");
        return;
    }
    FilterSamlSessionStore tokenStore = new FilterSamlSessionStore(request, facade, 100000, idMapper, deployment);
    boolean isEndpoint = request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml");
    SamlAuthenticator authenticator;
    if (isEndpoint) {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new SamlEndpoint(facade, deployment, sessionStore);
            }
        };

    } else {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new BrowserHandler(facade, deployment, sessionStore);
            }
        };
    }
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        log.fine("AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        HttpServletRequestWrapper wrapper = tokenStore.getWrap();
        chain.doFilter(wrapper, res);
        return;
    }
    if (outcome == AuthOutcome.LOGGED_OUT) {
        tokenStore.logoutAccount();
        String logoutPage = deployment.getLogoutPage();
        if (logoutPage != null) {
            if (PROTOCOL_PATTERN.matcher(logoutPage).find()) {
                response.sendRedirect(logoutPage);
                log.log(Level.FINE, "Redirected to logout page {0}", logoutPage);
            } else {
                RequestDispatcher disp = req.getRequestDispatcher(logoutPage);
                disp.forward(req, res);
            }
            return;
        }
        chain.doFilter(req, res);
        return;
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        log.fine("challenge");
        challenge.challenge(facade);
        return;
    }

    if (deployment.isIsPassive() && outcome == AuthOutcome.NOT_AUTHENTICATED) {
        log.fine("PASSIVE_NOT_AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        chain.doFilter(req, res);
        return;
    }

    if (!facade.isEnded()) {
        response.sendError(403);
    }

}