List of usage examples for javax.servlet ServletContext getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:com.util.ConvertJspToStringHtml.java
public static String generateHtml(String url, HttpServletRequest request, HttpServletResponse response) { String html = null;// ww w . j a v a 2 s . c o m try { BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(response); ServletContext context = request.getSession().getServletContext(); String urlEncode = response.encodeRedirectURL(url); RequestDispatcher dispatcher = context.getRequestDispatcher(urlEncode); dispatcher.include(request, wrapper); // html = ASCII2Unicode(StringEscapeUtils.unescapeHtml(wrapper.getOutput())); html = html.replaceAll("\\r\\n|\\r|\\n", ""); html = html.replaceAll(" ", ""); } catch (Exception e) { System.err.println(e.getMessage()); } return html; }
From source file:com.liferay.portal.struts.StrutsUtil.java
public static void include(String uri, ServletContext ctx, HttpServletRequest req, HttpServletResponse res) throws ServletException { String path = Constants.TEXT_HTML_DIR + uri; if (BrowserSniffer.is_wml(req)) { path = Constants.TEXT_WML_DIR + uri; }//from w w w . java2s. c om ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX)); if (portalCtx == null) { portalCtx = ctx; } RequestDispatcher rd = portalCtx.getRequestDispatcher(path); try { rd.include(req, res); } catch (IOException ioe) { } }
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 w w w . jav a 2s.c o 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:org.mskcc.cbio.portal.servlet.OncoPrintConverter.java
/** * Method called when exception occurs.//from w ww . j av a2s . c o m * * @param servletContext ServletContext * @param request HttpServletRequest * @param response HttpServletResponse * @param xdebug XDebug */ private static void forwardToErrorPage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, XDebug xdebug) throws ServletException, IOException { request.setAttribute("xdebug_object", xdebug); RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/WEB-INF/jsp/error.jsp"); dispatcher.forward(request, response); }
From source file:org.entando.entando.aps.system.services.controller.executor.AbstractWidgetExecutorService.java
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(); }
From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java
/** * Forward a request that was received by this servlet on to another JSP * page or servlet to continue handling the request. * /*from www . ja v a2 s . c om*/ * @param request * to be forwarded * @param response * that can be used for writing output to the client * @param destination * the context-relative URL to which the request is forwarded * @param params the request parameters. these will be added to the request */ public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, String destinationUrl, Hashtable<String, String[]> params) throws MetacatUtilException { destinationUrl += "?" + paramsToQuery(params); logMetacat.debug("Forwarding request to " + destinationUrl); ServletContext servletContext = request.getSession().getServletContext(); try { servletContext.getRequestDispatcher(destinationUrl).forward(request, response); } catch (IOException ioe) { throw new MetacatUtilException("RequestUtil.forwardRequest - I/O error when forwarding to " + destinationUrl + " : " + ioe.getMessage()); } catch (ServletException se) { throw new MetacatUtilException("RequestUtil.forwardRequest - Servlet error when forwarding to " + destinationUrl + " : " + se.getMessage()); } }
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 ww w . ja va 2s. com*/ 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:edu.ucsb.nceas.metacat.util.RequestUtil.java
/** * Forward a request that was received by this servlet on to another JSP * page or servlet to continue handling the request. In this case, the page * must be referenced in a paramter named "forwardto". If the qformat is * provided, the file will be retrieved from that skin. Otherwise, the file * will be retrieved from the system default skin. * /*from www . j a v a 2s.com*/ * For more specific file location, use: forwardRequest(request,response, destinationUrl, params) * * @param request * to be forwarded * @param response * that can be used for writing output to the client * @param params * the request parameters. these will be added to the request. */ public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, Hashtable<String, String[]> params) throws MetacatUtilException { String forwardTos[] = params.get("forwardto"); if (forwardTos == null || forwardTos[0].equals("")) { throw new MetacatUtilException( "RequestUtil.forwardRequest - forwardto must be set in parameters when forwarding."); } String forwardTo = forwardTos[0]; String qformat = null; String qformats[] = params.get("qformat"); if (qformats == null || qformats.length == 0) { try { qformat = PropertyService.getProperty("application.default-style"); } catch (PropertyNotFoundException pnfe) { qformat = "default"; logMetacat.warn("RequestUtil.forwardRequest - could not get property " + "'application.default-style'. Using 'default'"); } } else { qformat = qformats[0]; } String destinationUrl = "/style/skins/" + qformat + "/" + forwardTo; destinationUrl += "?" + paramsToQuery(params); logMetacat.debug("RequestUtil.forwardRequest - Forwarding request to " + destinationUrl); ServletContext servletContext = request.getSession().getServletContext(); try { servletContext.getRequestDispatcher(destinationUrl).forward(request, response); } catch (IOException ioe) { throw new MetacatUtilException("RequestUtil.forwardRequest - I/O error when forwarding to " + destinationUrl + " : " + ioe.getMessage()); } catch (ServletException se) { throw new MetacatUtilException("RequestUtil.forwardRequest - Servlet error when forwarding to " + destinationUrl + " : " + se.getMessage()); } }
From source file:pt.webdetails.cns.notifications.sparkl.kettle.baserver.web.utils.HttpConnectionHelper.java
protected static Response invokePlatformEndpoint(final String endpointPath, final String httpMethod, final Map<String, String> queryParameters) { Response response = new Response(); // get servlet context and request dispatcher ServletContext servletContext = null; RequestDispatcher requestDispatcher = null; try {/*w ww . j a v a 2 s. c om*/ Object context = PentahoSystem.getApplicationContext().getContext(); if (context instanceof ServletContext) { servletContext = (ServletContext) context; requestDispatcher = servletContext.getRequestDispatcher("/api" + endpointPath); } } catch (NoClassDefFoundError ex) { logger.error("Failed to get application servlet context", ex); return response; } if (requestDispatcher != null) { // create servlet request final InternalHttpServletRequest servletRequest = new InternalHttpServletRequest(httpMethod, "/pentaho", "/api", endpointPath); servletRequest.setAttribute("org.apache.catalina.core.DISPATCHER_TYPE", 2); // FORWARD = 2 for (Map.Entry<String, String> entry : queryParameters.entrySet()) { servletRequest.setParameter(entry.getKey(), entry.getValue()); } ServletRequestEvent servletRequestEvent = new ServletRequestEvent(servletContext, servletRequest); RequestContextListener requestContextListener = new RequestContextListener(); requestContextListener.requestInitialized(servletRequestEvent); // create servlet response ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final InternalHttpServletResponse servletResponse = new InternalHttpServletResponse(outputStream); try { // used for calculating the response time long startTime = System.currentTimeMillis(); requestDispatcher.forward(servletRequest, servletResponse); // get response time long responseTime = System.currentTimeMillis() - startTime; response.setStatusCode(servletResponse.getStatus()); response.setResult(servletResponse.getContentAsString()); response.setResponseTime(responseTime); } catch (ServletException ex) { logger.error("Failed ", ex); return response; } catch (IOException ex) { logger.error("Failed ", ex); return response; } finally { requestContextListener.requestDestroyed(servletRequestEvent); } } return response; }
From source file:password.pwm.http.servlet.configguide.ConfigGuideServlet.java
static void forwardToJSP(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException { final ConfigGuideBean configGuideBean = pwmRequest.getPwmApplication().getSessionStateService() .getBean(pwmRequest, ConfigGuideBean.class); if (configGuideBean.getStep() == GuideStep.LDAP_PERMISSIONS) { final LDAPPermissionCalculator ldapPermissionCalculator = new LDAPPermissionCalculator( ConfigGuideForm.generateStoredConfig(configGuideBean)); pwmRequest.setAttribute(PwmRequestAttribute.LdapPermissionItems, ldapPermissionCalculator); }// w w w.j a va 2 s . c o m final HttpServletRequest req = pwmRequest.getHttpServletRequest(); final ServletContext servletContext = req.getSession().getServletContext(); String destURL = '/' + PwmConstants.URL_JSP_CONFIG_GUIDE; destURL = destURL.replace("%1%", configGuideBean.getStep().toString().toLowerCase()); servletContext.getRequestDispatcher(destURL).forward(req, pwmRequest.getPwmResponse().getHttpServletResponse()); }