Example usage for javax.servlet RequestDispatcher forward

List of usage examples for javax.servlet RequestDispatcher forward

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher forward.

Prototype

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Source Link

Document

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Usage

From source file:com.liferay.portal.struts.StrutsUtil.java

public static void forward(String uri, ServletContext ctx, HttpServletRequest req, HttpServletResponse res)
        throws ServletException {

    if (!res.isCommitted()) {
        String path = Constants.TEXT_HTML_DIR + uri;
        if (BrowserSniffer.is_wml(req)) {
            path = Constants.TEXT_WML_DIR + uri;
        }//from ww  w  .jav a 2 s  .co  m

        ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));

        if (portalCtx == null) {
            portalCtx = ctx;
        }

        RequestDispatcher rd = portalCtx.getRequestDispatcher(path);

        try {
            rd.forward(req, res);
        } catch (IOException ioe1) {
            Logger.error(StrutsUtil.class, ioe1.getMessage(), ioe1);
        } catch (ServletException se1) {
            req.setAttribute(PageContext.EXCEPTION, se1.getRootCause());

            String errorPath = Constants.TEXT_HTML_DIR + Constants.COMMON_ERROR;
            if (BrowserSniffer.is_wml(req)) {
                path = Constants.TEXT_WML_DIR + Constants.COMMON_ERROR;
            }

            rd = portalCtx.getRequestDispatcher(errorPath);

            try {
                rd.forward(req, res);
            } catch (IOException ioe2) {
                Logger.error(StrutsUtil.class, ioe2.getMessage(), ioe2);
            } catch (ServletException se2) {
                throw se2;
            }
        }
    } else {
        _log.warn(uri + " is already committed");
    }
}

From source file:util.JSPUtil.java

public static void naytaJSP(HttpServletRequest request, HttpServletResponse response, String jspsivu) {
    RequestDispatcher dispatcher = null;
    //dispatcher = request.getRequestDispatcher("WEB-INF/jsp/muokkaatankki.jsp");
    dispatcher = request.getRequestDispatcher(jspsivu);
    try {/*  w w  w  .  ja v a  2 s  .  co m*/
        dispatcher.forward(request, response);
    } catch (ServletException ex) {
        Logger.getLogger(JSPUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(JSPUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:catalogo.Main.java

/**
 * Redirige la navegacin web a la pgina indicada en newUrl, pasndole en
 * request los datos que necesite/*w  w  w.j  av a2  s  .com*/
 *
 * @param newUrl
 * @param request
 * @param response
 */
private static void redirectTo(String newUrl, HttpServletRequest request, HttpServletResponse response) {
    try {
        RequestDispatcher dispatcher = null;
        dispatcher = request.getRequestDispatcher(newUrl);
        dispatcher.forward(request, response);
    } catch (ServletException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.micromata.genome.gwiki.page.impl.actionbean.ActionBeanUtils.java

protected static void createForward(ActionBean bean, GWikiContext pctx, String url, boolean redirect) {
    // String url = afw.getPath();
    try {/*w  w w  . ja  v a  2s.  c om*/
        if (redirect == true) {
            redirect(pctx, url);
        } else {
            RequestDispatcher rd = pctx.getCreatePageContext().getServletContext()
                    .getRequestDispatcher(pctx.localUrl(url));
            if (rd == null) {
            }
            rd.forward(pctx.getRequest(), pctx.getResponse());
        }
    } catch (ServletException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new RuntimeIOException(ex);
    }
}

From source file:com.zimbra.cs.service.formatter.HtmlFormatter.java

static void dispatchJspRest(Servlet servlet, UserServletContext context)
        throws ServiceException, ServletException, IOException {
    AuthToken auth = null;//from  w  ww.j  av a2 s. co m
    long expiration = System.currentTimeMillis() + AUTH_EXPIRATION;
    if (context.basicAuthHappened) {
        Account acc = context.getAuthAccount();
        if (acc instanceof GuestAccount) {
            auth = AuthToken.getAuthToken(acc.getId(), acc.getName(), null, ((GuestAccount) acc).getDigest(),
                    expiration);
        } else {
            auth = AuthProvider.getAuthToken(context.getAuthAccount(), expiration);
        }
    } else if (context.cookieAuthHappened) {
        auth = UserServlet.getAuthTokenFromCookie(context.req, context.resp, true);
    } else {
        auth = AuthToken.getAuthToken(GuestAccount.GUID_PUBLIC, null, null, null, expiration);
    }
    if (auth != null && context.targetAccount != null && context.targetAccount != context.getAuthAccount()) {
        auth.setProxyAuthToken(
                Provisioning.getInstance().getProxyAuthToken(context.targetAccount.getId(), null));
    }
    String authString = null;
    try {
        if (auth != null)
            authString = auth.getEncoded();
    } catch (AuthTokenException e) {
        throw new ServletException("error generating the authToken", e);
    }

    Account targetAccount = context.targetAccount;
    MailItem targetItem = context.target;
    String uri = (String) context.req.getAttribute("requestedPath");

    if (targetItem instanceof Mountpoint
            && ((Mountpoint) targetItem).getDefaultView() != MailItem.Type.APPOINTMENT) {
        Mountpoint mp = (Mountpoint) targetItem;
        Provisioning prov = Provisioning.getInstance();
        targetAccount = prov.getAccountById(mp.getOwnerId());
        Pair<Header[], HttpInputStream> remoteItem = UserServlet.getRemoteResourceAsStream(
                (auth == null) ? null : auth.toZAuthToken(), mp.getTarget(), context.extraPath);
        remoteItem.getSecond().close();
        String remoteItemId = null;
        String remoteItemType = null;
        String remoteItemName = null;
        String remoteItemPath = null;
        for (Header h : remoteItem.getFirst())
            if (h.getName().compareToIgnoreCase("X-Zimbra-ItemId") == 0)
                remoteItemId = h.getValue();
            else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemType") == 0)
                remoteItemType = h.getValue();
            else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemName") == 0)
                remoteItemName = h.getValue();
            else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemPath") == 0)
                remoteItemPath = h.getValue();

        context.req.setAttribute(ATTR_TARGET_ITEM_ID, remoteItemId);
        context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, remoteItemType);
        context.req.setAttribute(ATTR_TARGET_ITEM_NAME, remoteItemName);
        context.req.setAttribute(ATTR_TARGET_ITEM_PATH, remoteItemPath);
        context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, mp.getColor());
        context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, mp.getDefaultView().toByte());
        targetItem = null;
    }

    context.req.setAttribute(ATTR_INTERNAL_DISPATCH, "yes");
    context.req.setAttribute(ATTR_REQUEST_URI, uri != null ? uri : context.req.getRequestURI());
    context.req.setAttribute(ATTR_AUTH_TOKEN, authString);
    context.req.setAttribute(ATTR_CSRF_ENABLED, auth.isCsrfTokenEnabled());
    if (targetAccount != null) {
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, targetAccount.getName());
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_ID, targetAccount.getId());
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE,
                targetAccount.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_SKIN,
                targetAccount.getAttr(Provisioning.A_zimbraPrefSkin));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_LOCALE,
                targetAccount.getAttr(Provisioning.A_zimbraPrefLocale));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK,
                targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START,
                targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END,
                targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
    } else {
        // Useful when faking results - e.g. FREEBUSY html view for non-existent account
        if (context.fakeTarget != null) {
            context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, context.fakeTarget.getAccount());
        }
        com.zimbra.cs.account.Cos defaultCos = Provisioning.getInstance()
                .get(com.zimbra.common.account.Key.CosBy.name, Provisioning.DEFAULT_COS_NAME);
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE,
                defaultCos.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_SKIN,
                defaultCos.getAttr(Provisioning.A_zimbraPrefSkin));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_LOCALE,
                defaultCos.getAttr(Provisioning.A_zimbraPrefLocale));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK,
                defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START,
                defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END,
                defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
    }
    if (targetItem != null) {
        context.req.setAttribute(ATTR_TARGET_ITEM_ID, targetItem.getId());
        context.req.setAttribute(ATTR_TARGET_ITEM_PATH, targetItem.getPath());
        context.req.setAttribute(ATTR_TARGET_ITEM_NAME, targetItem.getName());
        context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, targetItem.getType().toString());

        context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, targetItem.getColor());
        if (targetItem instanceof Folder) {
            context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, ((Folder) targetItem).getDefaultView().toString());
        }
    } else {
        context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, Color.getMappedColor(null));
    }
    if (context.fakeTarget != null) { // Override to avoid address harvesting
        context.req.setAttribute(ATTR_TARGET_ITEM_PATH, context.fakeTarget.getPath());
        context.req.setAttribute(ATTR_TARGET_ITEM_NAME, context.fakeTarget.getName());
    }
    String mailUrl = PATH_MAIN_CONTEXT;
    if (WebSplitUtil.isZimbraServiceSplitEnabled()) {
        mailUrl = Provisioning.getInstance().getLocalServer().getWebClientURL() + PATH_JSP_REST_PAGE;
        HttpClient httpclient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient();
        /*
         * Retest the code with POST to check whether it works
        PostMethod postMethod = new PostMethod(mailUrl);
        Enumeration<String> attributeNames = context.req.getAttributeNames();
        List<Part> parts = new ArrayList<Part>();
        while(attributeNames.hasMoreElements())
        {
        String attrName = (String) attributeNames.nextElement();
        String attrValue = context.req.getAttribute(attrName).toString();
        Part part = new StringPart(attrName, attrValue);
        parts.add(part);
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
                
        HttpClientUtil.executeMethod(httpclient, postMethod);
        ByteUtil.copy(postMethod.getResponseBodyAsStream(), true, context.resp.getOutputStream(), true);
        */

        Enumeration<String> attributeNames = context.req.getAttributeNames();
        StringBuilder sb = new StringBuilder(mailUrl);
        sb.append("?");
        while (attributeNames.hasMoreElements()) {
            String attrName = attributeNames.nextElement();
            String attrValue = context.req.getAttribute(attrName).toString();
            sb.append(attrName).append("=").append(HttpUtil.urlEscape(attrValue)).append("&");
        }
        GetMethod postMethod = new GetMethod(sb.toString());

        HttpClientUtil.executeMethod(httpclient, postMethod);
        ByteUtil.copy(postMethod.getResponseBodyAsStream(), true, context.resp.getOutputStream(), false);
    } else {
        try {
            mailUrl = Provisioning.getInstance().getLocalServer().getMailURL();
        } catch (Exception e) {
        }
        ServletContext targetContext = servlet.getServletConfig().getServletContext().getContext(mailUrl);
        RequestDispatcher dispatcher = targetContext.getRequestDispatcher(PATH_JSP_REST_PAGE);
        dispatcher.forward(context.req, context.resp);
    }
}

From source file:com.lm.lic.manager.util.GenUtil.java

/**
 * @param request/*  ww  w .  j av  a2 s.  c om*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public static void toHell(HttpServletRequest request, HttpServletResponse response, String hellView)
        throws ServletException, IOException {
    javax.servlet.RequestDispatcher rd = request.getRequestDispatcher(hellView);
    rd.forward(request, response);
}

From source file:org.apache.hadoop.mapred.JSPUtil.java

/**
 * Sets error code SC_UNAUTHORIZED in response and forwards to
 * error page which contains error message and a back link.
 *///w ww .j  a v  a 2s.c  o  m
public static void setErrorAndForward(String errMsg, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("error.msg", errMsg);
    RequestDispatcher dispatcher = request.getRequestDispatcher("/job_authorization_error.jsp");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    dispatcher.forward(request, response);
}

From source file:com.day.cq.wcm.foundation.forms.FormResourceEdit.java

/**
 * Performs a Sling POST servlet modify operation, but on multiple
 * resources.//from   w  w  w  .  j  a v a2  s .  c o  m
 * <p>
 * The Sling POST servlet (more specifically, its modify operation) itself
 * can only handle a single resource (using the request resource) or by
 * using absolute paths to properties. This method will automatically
 * rewrite the parameters for the multiple resources and then call the Sling
 * POST servlet. All resources will be changed in a single transaction. The
 * response will look like the standard Sling POST response.
 * 
 * @param resources
 *            list of resources to bulk-edit
 * @param request
 *            current POST request, including the parameters for the Sling
 *            POST servlet
 * @param response
 *            current response
 * @throws ServletException
 * @throws IOException
 */
public static void multiPost(List<Resource> resources, SlingHttpServletRequest request,
        SlingHttpServletResponse response) throws ServletException, IOException {
    // 1. rewrite request params

    final RequestParameterMap originalParams = request.getRequestParameterMap();

    // group params by their property
    //
    // foo => foo = 1.1.2011
    //        foo@Delete = x
    //        foo@TypeHint = Date
    // bar => bar = test
    // ...
    Map<String, Map<String, RequestParameter[]>> groupedParams = new TreeMap<String, Map<String, RequestParameter[]>>();

    // 1. collect params, identify which to consider for writing

    boolean requireItemPrefix = false;

    Set<String> paramsToKeep = new HashSet<String>();
    Set<String> paramsToRemove = new HashSet<String>();

    for (Entry<String, RequestParameter[]> param : originalParams.entrySet()) {
        final String name = param.getKey();

        if (RP_OPERATION.equals(name)) {
            String op = originalParams.getValue(name).getString();
            // abort if operation is not modify as we can't bulk create/copy/move/checkin/checkout
            if (!"modify".equals(op)) {
                throw new ServletException(
                        "Only :operation=modify can be used when posting to multiple resources (was: '" + op
                                + "')");
            }
        }

        if (name.startsWith(ITEM_PREFIX_RELATIVE_CURRENT)) {
            requireItemPrefix = true;
        }

        // if param name ends with "@something", the property name is the part before it
        final int pos = name.indexOf("@");
        String propName = pos >= 0 ? name.substring(0, pos) : name;

        // add to map or use already existing entry for this property
        Map<String, RequestParameter[]> map = groupedParams.get(propName);
        if (map == null) {
            groupedParams.put(propName, map = new TreeMap<String, RequestParameter[]>());
        }
        map.put(name, param.getValue());

        // properties to write end with @Write
        if (name.endsWith(WRITE_SUFFIX)) {
            paramsToKeep.add(propName);
            map.remove(name); // we don't need the "@Write" param in the sling post servlet
        }

        // remove form params (for cleaner request, technically not needed, as they are ignored by sling anyway)
        if (FormsConstants.REQUEST_PROPERTY_FORMID.equals(name)
                || FormsConstants.REQUEST_PROPERTY_FORM_START.equals(name) || RESOURCES_PARAM.equals(name)) {
            continue;
        }

        // all special :something sling post params must be kept
        if (name.startsWith(RP_PREFIX)) {
            paramsToKeep.add(name);
        }

        // @MoveFrom must be ignored (doesn't work for multiple resources)
        if (name.endsWith(SUFFIX_MOVE_FROM)) {
            paramsToRemove.add(propName);
        }
    }

    // 2. remove params that should not be written

    for (Iterator<String> iter = groupedParams.keySet().iterator(); iter.hasNext();) {
        String name = iter.next();
        if (!paramsToKeep.contains(name) || paramsToRemove.contains(name)) {
            iter.remove();
        }
    }

    // 3. rewrite params for each resource

    ParameterMap params = new ParameterMap();

    log.debug("posting to multiple resources:");

    boolean first = true;
    for (Resource r : resources) {
        String path = r.getPath();
        log.debug("{}", path);

        for (Map<String, RequestParameter[]> p : groupedParams.values()) {
            for (Entry<String, RequestParameter[]> param : p.entrySet()) {
                String name = param.getKey();

                // include :params and absolute paths only once and don't rewrite them
                if (name.startsWith(RP_PREFIX) || name.startsWith(ITEM_PREFIX_ABSOLUTE)) {
                    if (first) {
                        params.put(name, param.getValue());
                    }
                } else if (requireItemPrefix) {
                    // only use params with item prefix (and skip others)
                    if (name.startsWith(ITEM_PREFIX_RELATIVE_CURRENT)) {
                        params.put(path + "/" + name.substring(ITEM_PREFIX_RELATIVE_CURRENT.length()),
                                param.getValue());
                    } else if (name.startsWith(ITEM_PREFIX_RELATIVE_PARENT)) {
                        path = Text.getRelativeParent(path, 1);
                        params.put(path + "/" + name.substring(ITEM_PREFIX_RELATIVE_PARENT.length()),
                                param.getValue());
                    }
                } else /* if (!requireItemPrefix) */ {
                    // rewrite all params
                    params.put(path + "/" + name, param.getValue());
                }
            }
        }
        first = false;
    }

    if (log.isDebugEnabled()) {
        log.debug("rewritten parameters:");
        logParams(params);
    }

    // 4. send new internal request to sling post servlet

    // forward but make sure we remove the "forms" selector and the suffix
    RequestDispatcherOptions options = new RequestDispatcherOptions();
    options.setReplaceSelectors("");
    options.setReplaceSuffix("");
    RequestDispatcher dispatcher = request.getRequestDispatcher(request.getResource(), options);
    dispatcher.forward(new CustomParameterRequest(request, params), response);
}

From source file:com.feilong.servlet.http.RequestUtil.java

/**
 * ? {@link RequestDispatcher} ??,Servlet??????.
 * /* ww  w  . j  a  v a2 s .c o m*/
 * <p>
 * Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.<br>
 * This method allows one servlet to do preliminary processing of a request and another resource to generate the response.
 * </p>
 * 
 * <p>
 * For a <code>RequestDispatcher</code> obtained via <code>getRequestDispatcher()</code>, the <code>ServletRequest</code> object has its
 * path elements and parameters adjusted to match the path of the target resource.
 * </p>
 * 
 * <p>
 * <code>forward</code> should be called before the response has been committed to the client (before response body output has been
 * flushed). If the response already has been committed, this method throws an <code>IllegalStateException</code>. Uncommitted output in
 * the response buffer is automatically cleared before the forward.
 * </p>
 * 
 * <p>
 * The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be
 * subclasses of the {@link ServletRequestWrapper} or {@link ServletResponseWrapper} classes that wrap them.
 * </p>
 * 
 * @param path
 *            the path
 * @param request
 *            a {@link ServletRequest} object that represents the request the client makes of the servlet
 * @param response
 *            a {@link ServletResponse} object,that represents the response the servlet returns to the client
 * @since 1.2.2
 */
public static void forward(String path, HttpServletRequest request, HttpServletResponse response) {
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
    try {
        requestDispatcher.forward(request, response);
    } catch (ServletException | IOException e) {
        LOGGER.error("", e);
        throw new RequestException(e);
    }
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Forward to our standard error message page with an internationalized message. Note that this <em>doesn't</em>
 * throw ForwardedToErrorPage, it is the job of whoever calls this to do that if not within a JSP page (a JSP page
 * can just return immediately). The text involved must be HTML-escaped before passing to this method.
 *
 * @param context The context that the error happened in (the JSP-defined pageContext, typically)
 * @param i18n The i18n information//from  w w w.  j  ava  2 s.  co m
 * @param label An i18n label for the error. This label should begin with "errormsg;".
 * @param args Any extra args for i18n. These must be valid HTML.
 * @throws IOFailure If the forward fails.
 */
public static void forwardWithRawErrorMessage(PageContext context, I18n i18n, String label, Object... args) {
    // Note that we may not want to be to strict here
    // as otherwise information could be lost.
    ArgumentNotValid.checkNotNull(context, "context");
    ArgumentNotValid.checkNotNull(I18N, "I18N");
    ArgumentNotValid.checkNotNull(label, "label");
    ArgumentNotValid.checkNotNull(args, "args");

    String msg = i18n.getString(context.getResponse().getLocale(), label, args);
    context.getRequest().setAttribute("message", msg);
    RequestDispatcher rd = context.getServletContext().getRequestDispatcher("/message.jsp");
    try {
        rd.forward(context.getRequest(), context.getResponse());
    } catch (IOException e) {
        final String errormsg = "Failed to forward on error " + msg;
        log.warn(errormsg, e);
        throw new IOFailure(errormsg, e);
    } catch (ServletException e) {
        final String errormsg = "Failed to forward on error " + msg;
        log.warn(errormsg, e);
        throw new IOFailure(errormsg, e);
    }
}