javax.servlet.RequestDispatcher类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(15.0k)|赞(0)|评价(0)|浏览(96)

本文整理了Java中javax.servlet.RequestDispatcher类的一些代码示例,展示了RequestDispatcher类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。RequestDispatcher类的具体详情如下:
包路径:javax.servlet.RequestDispatcher
类名称:RequestDispatcher

RequestDispatcher介绍

[英]Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.
[中]定义一个对象,该对象接收来自客户端的请求,并将它们发送到服务器上的任何资源(如servlet、HTML文件或JSP文件)。servlet容器创建RequestDispatcher对象,该对象用作位于特定路径或由特定名称给定的服务器资源的包装器。
该接口旨在包装servlet,但servlet容器可以创建RequestDispatcher对象来包装任何类型的资源。

代码示例

代码示例来源:origin: DeemOpen/zkui

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest) req;
  HttpServletResponse response = (HttpServletResponse) res;
  if (!request.getRequestURI().contains("/login") && !request.getRequestURI().contains("/acd/appconfig")) {
    RequestDispatcher dispatcher;
    HttpSession session = request.getSession();
    if (session != null) {
      if (session.getAttribute("authName") == null || session.getAttribute("authRole") == null) {
        response.sendRedirect("/login");
        return;
      }
    } else {
      request.setAttribute("fail_msg", "Session timed out!");
      dispatcher = request.getRequestDispatcher("/Login");
      dispatcher.forward(request, response);
      return;
    }
  }
  fc.doFilter(req, res);
}

代码示例来源:origin: jenkinsci/jenkins

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rsp = (HttpServletResponse) response;
String authorization = req.getHeader("Authorization");
String path = req.getServletPath();
if(authorization==null || req.getUserPrincipal() !=null || path.startsWith("/secured/")
|| !Jenkins.getInstance().isUseSecurity()) {
    chain.doFilter(request,response);
  } finally {
    SecurityContextHolder.clearContext();
  rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  rsp.setHeader("WWW-Authenticate","Basic realm=\"Jenkins user\"");
  return;
      chain.doFilter(request,response);
    } finally {
      SecurityContextHolder.clearContext();
rsp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
rsp.setHeader("Location",path);
RequestDispatcher d = servletContext.getRequestDispatcher("/j_security_check?j_username="+
  URLEncoder.encode(username,"UTF-8")+"&j_password="+URLEncoder.encode(password,"UTF-8"));
d.include(req,rsp);

代码示例来源:origin: spring-projects/spring-framework

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
  ServletContext servletContext = getServletContext();
  Assert.state(servletContext != null, "No ServletContext");
  RequestDispatcher rd = servletContext.getNamedDispatcher(this.servletName);
  if (rd == null) {
    throw new ServletException("No servlet with name '" + this.servletName + "' defined in web.xml");
  }
  // If already included, include again, else forward.
  if (useInclude(request, response)) {
    rd.include(request, response);
    if (logger.isTraceEnabled()) {
      logger.trace("Included servlet [" + this.servletName +
          "] in ServletForwardingController '" + this.beanName + "'");
    }
  }
  else {
    rd.forward(request, response);
    if (logger.isTraceEnabled()) {
      logger.trace("Forwarded to servlet [" + this.servletName +
          "] in ServletForwardingController '" + this.beanName + "'");
    }
  }
  return null;
}

代码示例来源:origin: oblac/jodd

/**
 * Renders the view by dispatching to the target JSP.
 */
@Override
protected void renderView(final ActionRequest actionRequest, final String target) throws Exception {
  HttpServletRequest request = actionRequest.getHttpServletRequest();
  HttpServletResponse response = actionRequest.getHttpServletResponse();
  RequestDispatcher dispatcher = request.getRequestDispatcher(target);
  if (dispatcher == null) {
    response.sendError(SC_NOT_FOUND, "Result not found: " + target);	// should never happened
    return;
  }
  // If we're included, then include the view, otherwise do forward.
  // This allow the page to, for example, set content type.
  if (DispatcherUtil.isPageIncluded(request, response)) {
    dispatcher.include(request, response);
  } else {
    dispatcher.forward(request, response);
  }
}

代码示例来源:origin: spring-projects/spring-framework

throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
    "]: Check that the corresponding file exists within your web application archive!");
response.setContentType(getContentType());
if (logger.isDebugEnabled()) {
  logger.debug("Including [" + getUrl() + "]");
rd.include(request, response);
  logger.debug("Forwarding to [" + getUrl() + "]");
rd.forward(request, response);

代码示例来源:origin: org.eclipse.jetty/jetty-security

Response base_response = base_request.getResponse();
String uri = request.getRequestURI();
if (uri==null)
  uri=URIUtil.SLASH;
  return new DeferredAuthentication(this);
if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(),request.getPathInfo())) &&!DeferredAuthentication.isDeferred(response))
  return new DeferredAuthentication(this);
      synchronized(session)
        nuri = (String) session.getAttribute(__J_URI);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
      response.setHeader(HttpHeader.CACHE_CONTROL.asString(),HttpHeaderValue.NO_CACHE.asString());
      response.setDateHeader(HttpHeader.EXPIRES.asString(),1);
      dispatcher.forward(new FormRequest(request), new FormResponse(response));
      session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
    response.setHeader(HttpHeader.CACHE_CONTROL.asString(),HttpHeaderValue.NO_CACHE.asString());
    response.setDateHeader(HttpHeader.EXPIRES.asString(),1);
    dispatcher.forward(new FormRequest(request), new FormResponse(response));

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

throws ServletException, IOException {
String contextPath = request.getContextPath();
String requestURIWithoutContext;
if (request.getContextPath() != null) {
  requestURIWithoutContext = request.getRequestURI().substring(request.getContextPath().length());
} else {
  requestURIWithoutContext = request.getRequestURI();
  extensionManager.getProxy().processPreRedirect(request, response, url);
  if (URLRedirectType.FORWARD == handler.getUrlRedirectType()) {
    request.getRequestDispatcher(handler.getNewURL()).forward(request, response);               
  } else if (URLRedirectType.REDIRECT_PERM == handler.getUrlRedirectType()) {
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader( "Location", url);
    response.setHeader( "Connection", "close" );
  } else if (URLRedirectType.REDIRECT_TEMP == handler.getUrlRedirectType()) {
    response.sendRedirect(url);             
  filterChain.doFilter(request, response);

代码示例来源:origin: apache/drill

@GET
 @Path("/logout")
 public Viewable logout(@Context HttpServletRequest req,
   @Context HttpServletResponse resp) throws Exception {
  final HttpSession session = req.getSession();
  if (session != null) {
   session.invalidate();
  }
  req.getRequestDispatcher("/login").forward(req, resp);
  return null;
 }
}

代码示例来源:origin: org.eclipse.jetty.aggregate/jetty-all-server

public void doFilter(ServletRequest request,
           ServletResponse response,
           FilterChain chain)
throws IOException, ServletException
{
  String path=((HttpServletRequest)request).getServletPath();
  if (welcome!=null && path.endsWith("/"))
    request.getRequestDispatcher(path+welcome).forward(request,response);
  else
    chain.doFilter(request, response);
}

代码示例来源:origin: lxy-go/SpringBoot

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  Object user = request.getSession().getAttribute("loginUser");
  if(user!=null){
    //已经登录
    return true;
  }
  //未经过验证
  request.setAttribute("msg", "没权限请先登录");
  request.getRequestDispatcher("/index.html").forward(request, response);
  return false;
}

代码示例来源:origin: cloudfoundry/uaa

protected void validateParamsAndContinue(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
  for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
    if (entry.getValue() != null && entry.getValue().length >0) {
      for (String s : entry.getValue()) {
        if (hasText(s) && s.contains(NULL_STRING)) {
          response.setStatus(400);
          request.setAttribute("error_message_code", "request.invalid_parameter");
          request.getRequestDispatcher("/error").forward(request,response);
          return;
        }
      }
    }
  }
  chain.doFilter(request, response);
}

代码示例来源:origin: stanfordnlp/CoreNLP

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 if (request.getCharacterEncoding() == null) {
  request.setCharacterEncoding("utf-8");
 }
 response.setContentType("text/html; charset=UTF-8");
 this.getServletContext().getRequestDispatcher("/header.jsp").
  include(request, response);
 addResults(request, response);
 this.getServletContext().getRequestDispatcher("/footer.jsp").
  include(request, response);
}

代码示例来源:origin: com.liferay.portal/com.liferay.portal.kernel

@Override
public boolean include(
    HttpServletRequest request, HttpServletResponse response,
    String template)
  throws Exception {
  String jspPath = getJspPath(request, template);
  if (Validator.isNull(jspPath)) {
    return false;
  }
  ResourceBundleLoader resourceBundleLoader =
    (ResourceBundleLoader)request.getAttribute(
      WebKeys.RESOURCE_BUNDLE_LOADER);
  ServletContext servletContext = getServletContext();
  RequestDispatcher requestDispatcher =
    servletContext.getRequestDispatcher(jspPath);
  try {
    request.setAttribute(
      WebKeys.RESOURCE_BUNDLE_LOADER, getResourceBundleLoader());
    requestDispatcher.include(request, response);
    return true;
  }
  catch (ServletException se) {
    _log.error("Unable to include JSP " + jspPath, se);
    throw new IOException("Unable to include " + jspPath, se);
  }
  finally {
    request.setAttribute(
      WebKeys.RESOURCE_BUNDLE_LOADER, resourceBundleLoader);
  }
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void test_invalid_password_match() throws Exception {
  PasswordConfirmationException pe = new PasswordConfirmationException(messageCode, email);
  BadCredentialsException be = new BadCredentialsException("", pe);
  entryPoint.commence(request, response, be);
  verify(request, times(1)).getRequestDispatcher(eq("/reset_password"));
  verify(request, times(1)).setAttribute(eq("message_code"), eq(messageCode));
  verify(requestDispatcher, timeout(1)).forward(any(HttpServletRequest.class), same(response));
  verify(response, times(1)).setStatus(eq(HttpStatus.UNPROCESSABLE_ENTITY.value()));
}

代码示例来源:origin: org.kantega.openaksess/openaksess-commons

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  String uri = req.getRequestURI().substring(req.getContextPath().length());
  Matcher m = resourcePattern.matcher(uri);
  if(m.find() && isLegal(uri)) {
    final String realUri = m.group(2);
    res.setDateHeader("Expires", System.currentTimeMillis() + YEAR);
    req.getRequestDispatcher(realUri).forward(request, response);
    return;
  }
  chain.doFilter(req, res);
}

代码示例来源:origin: pentaho/mondrian

throws ServletException, IOException
String queryName = request.getParameter("query");
ResultCache rc =
  ResultCache.getInstance(
    request.getSession(), getServletContext(), queryName);
Query query = rc.getQuery();
query = query.clone();
rc.setDirty();
String operation = request.getParameter("operation");
if (operation.equals("expand")) {
  String memberName = request.getParameter("member");
  redirect = "/adhoc.jsp";
response.setHeader("Content-Type", "text/html");
getServletContext().getRequestDispatcher(redirect).include(
  request, response);

代码示例来源:origin: stackoverflow.com

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {

 // get data from request querystring
 String accountId = req.getParameter("accountid");

 // populate your object with it (you might want to check it's not null)
 AccountBean accountBean = new AccountBean(accountId);

 // store data in session
 HttpSession session = req.getSession();
 session.setAttribute("accountBean", accountBean);

 // forward the request (not redirect)
 RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
 dispatcher.forward(req, resp);
}

代码示例来源:origin: javaee-samples/javaee7-samples

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  try (PrintWriter out = response.getWriter()) {
    out.println("<!DOCTYPE html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<title>CDI Scopes</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>CDI Scopes</h1>");
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ServerServlet");
    out.println("<h2>First request</h2>");
    dispatcher.include(request, response);
    out.println("<h2>Second request</h2>");
    dispatcher.include(request, response);
    out.println("</body>");
    out.println("</html>");
  }
}

代码示例来源:origin: cloudfoundry/uaa

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
  try {
    SAMLMessageContext context = contextProvider.getLocalAndPeerEntity(request, response);
    if (isECP(context)) {
      initializeECP(context, e);
    } else if (isDiscovery(context)) {
      initializeDiscovery(context);
    } else {
      initializeSSO(context, e);
    }
  } catch (SamlBindingNotSupportedException e1) {
    request.setAttribute("error_message_code", "error.sso.supported.binding");
    response.setStatus(400);
    request.getRequestDispatcher("/saml_error").include(request, response);
  } catch (SAMLException e1) {
    logger.debug("Error initializing entry point", e1);
    throw new ServletException(e1);
  } catch (MetadataProviderException e1) {
    logger.debug("Error initializing entry point", e1);
    throw new ServletException(e1);
  } catch (MessageEncodingException e1) {
    logger.debug("Error initializing entry point", e1);
    throw new ServletException(e1);
  }
}

代码示例来源:origin: pentaho/mondrian

throws ServletException, java.io.IOException
String queryName = request.getParameter("query");
request.setAttribute("query", queryName);
if (queryName != null) {
  processTransform(request, response);
  return;
String queryString = request.getParameter("queryString");
request.setAttribute("queryString", queryString);
mondrian.olap.Connection mdxConnection = null;
request.setAttribute("result", html.toString());
response.setHeader("Content-Type", "text/html");
getServletContext().getRequestDispatcher("/adhoc.jsp").include(
  request, response);

相关文章