javax.servlet.RequestDispatcher Java Examples

The following examples show how to use javax.servlet.RequestDispatcher. 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: InternalServerErrorControllerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenericError() {
    MessageService messageService = new YamlMessageService();
    InternalServerErrorController errorController = new InternalServerErrorController(messageService);

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, new Exception("Hello"));
    request.setAttribute(ErrorUtils.ATTR_ERROR_STATUS_CODE, 523);
    request.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, "/uri");

    ResponseEntity<ApiMessageView> response = errorController.error(request);

    assertEquals(523,  response.getStatusCodeValue());
    assertEquals("org.zowe.apiml.common.internalRequestError",  response.getBody().getMessages().get(0).getMessageKey());
    assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("Hello"));
    assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("/uri"));
}
 
Example #2
Source File: Request.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Notify interested listeners that attribute has been removed.
 *
 * @param name Attribute name
 * @param value Attribute value
 */
private void notifyAttributeRemoved(String name, Object value) {
    Context context = getContext();
    Object listeners[] = context.getApplicationEventListeners();
    if ((listeners == null) || (listeners.length == 0)) {
        return;
    }
    ServletRequestAttributeEvent event =
            new ServletRequestAttributeEvent(context.getServletContext(),
                    getRequest(), name, value);
    for (int i = 0; i < listeners.length; i++) {
        if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
            continue;
        }
        ServletRequestAttributeListener listener =
                (ServletRequestAttributeListener) listeners[i];
        try {
            listener.attributeRemoved(event);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            // Error valve will pick this exception up and display it to user
            attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
            context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
        }
    }
}
 
Example #3
Source File: Request.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Notify interested listeners that attribute has been removed.
 */
private void notifyAttributeRemoved(String name, Object value) {
    Object listeners[] = context.getApplicationEventListeners();
    if ((listeners == null) || (listeners.length == 0)) {
        return;
    }
    ServletRequestAttributeEvent event =
      new ServletRequestAttributeEvent(context.getServletContext(),
                                       getRequest(), name, value);
    for (int i = 0; i < listeners.length; i++) {
        if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
            continue;
        }
        ServletRequestAttributeListener listener =
            (ServletRequestAttributeListener) listeners[i];
        try {
            listener.attributeRemoved(event);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
            // Error valve will pick this exception up and display it to user
            attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
        }
    }
}
 
Example #4
Source File: UserController.java    From SA47 with The Unlicense 6 votes vote down vote up
private void processRequest(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	try {
		UserService service = new UserService();
		String command = request.getPathInfo();
		switch (command) {
		case "/load":
			ArrayList<User> list = service.findUsers();
			request.setAttribute("users", list);
			RequestDispatcher rd = request.getRequestDispatcher("/views/UserCRUD.jsp");
			rd.forward(request, response);
			break;
		default:
			break;
		}
	} catch (NotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #5
Source File: RendererHelper.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Renders a URL and returns the content generated as a string
 * @param url content to generate
 * @param req incoming request
 * @param resp current respnose
 * @return rendered content
 * @throws ServletException something goes wrong
 * @throws IOException something goes wrong
 */
public static String renderRequest(String url, HttpServletRequest req,
        HttpServletResponse resp) throws ServletException, IOException {
    String retval = null;
    RequestDispatcher dispatcher = req.getRequestDispatcher(url);
    if (dispatcher != null) {
        CachingResponseWrapper wrapper =
            new CachingResponseWrapper(resp);
        dispatcher.include(req, wrapper);
        retval = wrapper.getCachedContent();
        if (retval != null) {
            retval = retval.trim();
        }
    }
    return retval;
}
 
Example #6
Source File: JspServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void handleMissingResource(HttpServletRequest request,
        HttpServletResponse response, String jspUri)
        throws ServletException, IOException {

    String includeRequestUri =
        (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);

    if (includeRequestUri != null) {
        // This file was included. Throw an exception as
        // a response.sendError() will be ignored
        String msg =
            Localizer.getMessage("jsp.error.file.not.found",jspUri);
        // Strictly, filtering this is an application
        // responsibility but just in case...
        throw new ServletException(Escape.htmlElementContent(msg));
    } else {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    request.getRequestURI());
        } catch (IllegalStateException ise) {
            log.error(Localizer.getMessage("jsp.error.file.not.found",
                    jspUri));
        }
    }
    return;
}
 
Example #7
Source File: JspRuntimeLibrary.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Returns the value of the javax.servlet.error.exception request
 * attribute value, if present, otherwise the value of the
 * javax.servlet.jsp.jspException request attribute value.
 *
 * This method is called at the beginning of the generated servlet code
 * for a JSP error page, when the "exception" implicit scripting language
 * variable is initialized.
 * @param request The Servlet request
 * @return the throwable in the error attribute if any
 */
public static Throwable getThrowable(ServletRequest request) {
    Throwable error = (Throwable) request.getAttribute(
            RequestDispatcher.ERROR_EXCEPTION);
    if (error == null) {
        error = (Throwable) request.getAttribute(PageContext.EXCEPTION);
        if (error != null) {
            /*
             * The only place that sets JSP_EXCEPTION is
             * PageContextImpl.handlePageException(). It really should set
             * SERVLET_EXCEPTION, but that would interfere with the
             * ErrorReportValve. Therefore, if JSP_EXCEPTION is set, we
             * need to set SERVLET_EXCEPTION.
             */
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, error);
        }
    }

    return error;
}
 
Example #8
Source File: DefaultAsyncDispatcher.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void dispatch() {
    AsyncContext asyncContext = asyncStartRequest.getAsyncContext();
    RequestDispatcher requestDispatcher = webApplication.getRequestDispatcher(path);

    new Thread(() -> {
        Thread.currentThread().setContextClassLoader(webApplication.getClassLoader());

        try {
            requestDispatcher.forward(addAsyncWrapper(asyncStartRequest), asyncStartResponse);
        } catch (Throwable t) {
            // TODO: Notify listeners
        }

        // TODO: check complete not already called
        asyncContext.complete();

    }).start();
}
 
Example #9
Source File: WebdavServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
protected String getRelativePath(HttpServletRequest request, boolean allowEmptyPath) {
    String pathInfo;

    if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
        // For includes, get the info from the attributes
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
    } else {
        pathInfo = request.getPathInfo();
    }

    StringBuilder result = new StringBuilder();
    if (pathInfo != null) {
        result.append(pathInfo);
    }
    if (result.length() == 0) {
        result.append('/');
    }

    return result.toString();
}
 
Example #10
Source File: ServletForwardingController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	RequestDispatcher rd = getServletContext().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.isDebugEnabled()) {
			logger.debug("Included servlet [" + this.servletName +
					"] in ServletForwardingController '" + this.beanName + "'");
		}
	}
	else {
		rd.forward(request, response);
		if (logger.isDebugEnabled()) {
			logger.debug("Forwarded to servlet [" + this.servletName +
					"] in ServletForwardingController '" + this.beanName + "'");
		}
	}
	return null;
}
 
Example #11
Source File: CategoriaControle.java    From redesocial with MIT License 6 votes vote down vote up
private void editar(HttpServletRequest request, HttpServletResponse response) throws Exception{
    try {
        Integer id = Integer.parseInt(request.getParameter("id"));

        CategoriaBO categoriaBO = new CategoriaBO();
        Categoria categoria = categoriaBO.selecionar(id);

        request.setAttribute("categoria", categoria);

        request.setAttribute("mensagem", "Registro selecionado com sucesso");
    } catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/categorias/cadastro.jsp");
    rd.forward(request, response);
}
 
Example #12
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 #13
Source File: SearchReaderBeforeEdit.java    From Online-Library-System with GNU General Public License v2.0 6 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");

	PrintWriter out = response.getWriter();
	try {
		int readerId = Integer.parseInt(request.getParameter("account"));// 获取参数
		ReaderDAO readerDAO = new ReaderDAO();
		Reader reader = readerDAO.getReaderById(readerId);// 实例化属性
		request.setAttribute("readerEntity", reader);// 设置request属性,仅在下一个被请求页面中使用该属性
		RequestDispatcher dispatcher = request.getRequestDispatcher("searchReaderBeforeEdit.jsp");
		dispatcher.forward(request, response);// 转发
	} catch (Exception e) {
		System.out.println("--SearchReaderBeforeEdit--doPost(),传参错误:很有可能是reader账号没有写对");
		out.print("<script language='javascript'>" + "alert('Reader ID may be invalid, please input again!');"
				+ "window.location.href='searchReaderBeforeEdit.jsp';" + "</script>");
	}
}
 
Example #14
Source File: ServletRelativePathAttribute.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if(src == null) {
        return RelativePathAttribute.INSTANCE.readAttribute(exchange);
    }
    String path = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_PATH_INFO);
    String sp = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH);
    if(path == null && sp == null) {
        return RelativePathAttribute.INSTANCE.readAttribute(exchange);
    }
    if(sp == null) {
        return path;
    } else if(path == null) {
        return sp;
    } else {
        return sp + path;
    }
}
 
Example #15
Source File: CategoriaControle.java    From redesocial with MIT License 6 votes vote down vote up
private void cadastrar(HttpServletRequest request, HttpServletResponse response) throws Exception{
    Categoria categoria = new Categoria();

    if (!"".equals(request.getParameter("id").trim())){
        categoria.setId(Integer.parseInt(request.getParameter("id")));
    }

    categoria.setDescricao(request.getParameter("descricao"));

    request.setAttribute("categoria", categoria);

    if (categoria.getId() == null){
        this.inserir(categoria, request, response);
    } else {
        this.alterar(categoria, request, response);
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/categorias/cadastro.jsp");
    rd.forward(request, response);
}
 
Example #16
Source File: RequestForwardUtils.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void forwardRequestRelativeToCurrentContext(String fwdPath, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {

  if (fwdPath == null || request == null || response == null) {
    String msg = "Path, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToCurrentContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();

  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = request.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example #17
Source File: LoginControle.java    From redesocial with MIT License 6 votes vote down vote up
private void logar(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String email = request.getParameter("email");
    String senha = request.getParameter("senha");
    
    UsuarioBO bo = new UsuarioBO();
    Usuario usuario = bo.logar(email, senha);
    
    if (usuario != null){
        request.setAttribute("usuario", usuario);
        
        request.getSession().setAttribute("usuario", usuario);
        
        response.sendRedirect("./FeedControle?operacao=Atualizar");
    } else {
        request.setAttribute("mensagem", "Usuário ou senha inválidos");
        
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
        rd.forward(request, response);
    }
}
 
Example #18
Source File: JspServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void handleMissingResource(HttpServletRequest request,
        HttpServletResponse response, String jspUri)
        throws ServletException, IOException {

    String includeRequestUri =
        (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);

    if (includeRequestUri != null) {
        // This file was included. Throw an exception as
        // a response.sendError() will be ignored
        String msg =
            Localizer.getMessage("jsp.error.file.not.found",jspUri);
        // Strictly, filtering this is an application
        // responsibility but just in case...
        throw new ServletException(SecurityUtil.filter(msg));
    } else {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    request.getRequestURI());
        } catch (IllegalStateException ise) {
            log.error(Localizer.getMessage("jsp.error.file.not.found",
                    jspUri));
        }
    }
    return;
}
 
Example #19
Source File: PortalDispatcher.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     try {
         String requestURI = request.getRequestURI();
ReleaseConfig issueInfo = getIssueInfo(requestURI);
if(issueInfo == null) {
	response.sendRedirect(THE_404_URL);
	return;
}

// 检测相应门户是否可以使用匿名用户访问
Long portalId = issueInfo.getPortal().getId(), pageId = null;
if(issueInfo.getPage() != null) {
	pageId = issueInfo.getPage().getId();
}

if ( canPortalBrowseByAnonymous(portalId, pageId) ) {
	String redirectPage = getRedirectPath(issueInfo);
          log.debug("访问门户发布地址被转向至真实地址:" + redirectPage );

          RequestDispatcher rd = request.getRequestDispatcher(redirectPage);
          rd.forward(request, response); // 控制权转发
}
else {
	response.sendRedirect(THE_LOGIN_URL);
}
 
         /* 
          * RequestDispatcher.forward()方法和HttpServletResponse.sendRedirect()方法的区别是:
          * 前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;
          * 后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接,这样,从浏览器的地址栏中可以看到跳转后的链接地址。
          * 所以,前者更加高效,在前者可以满足需要时,尽量使用Request Dispatcher.forward()方法,并且,
          * 这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用 
          * HttpServletResponse.sendRedirect()方法。
          */
     } catch (Exception e) {
         throw new BusinessServletException(e);
     }
 }
 
Example #20
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String getOriginalRequestURI() {
    String uri = (String) getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    if(uri != null) {
        return uri;
    }
    uri = (String) getAttribute(AsyncContext.ASYNC_REQUEST_URI);
    if(uri != null) {
        return uri;
    }
    return getRequestURI();
}
 
Example #21
Source File: InternalResourceView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Render the internal resource given the specified model.
 * This includes setting the model as request attributes.
 * 在给定指定模型的情况下呈现内部资源。这包括将模型设置为请求属性
 */
@Override
protected void renderMergedOutputModel(
		Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

	// Expose the model object as request attributes.
	exposeModelAsRequestAttributes(model, request);

	// Expose helpers as request attributes, if any.
	exposeHelpers(request);

	// Determine the path for the request dispatcher.
	String dispatcherPath = prepareForRendering(request, response);

	// Obtain a RequestDispatcher for the target resource (typically a JSP).
	RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
	if (rd == null) {
		throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
				"]: Check that the corresponding file exists within your web application archive!");
	}

	// If already included or response already committed, perform include, else forward.
	if (useInclude(request, response)) {
		response.setContentType(getContentType());
		if (logger.isDebugEnabled()) {
			logger.debug("Including [" + getUrl() + "]");
		}
		rd.include(request, response);
	}

	else {
		// Note: The forwarded resource is supposed to determine the content type itself.
		if (logger.isDebugEnabled()) {
			logger.debug("Forwarding to [" + getUrl() + "]");
		}
		rd.forward(request, response);
	}
}
 
Example #22
Source File: ServletForwardingController.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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;
}
 
Example #23
Source File: ViewResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testInternalResourceViewResolverWithSpecificContextBeans() throws Exception {
	MockServletContext sc = new MockServletContext();
	final StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.registerSingleton("myBean", TestBean.class);
	wac.registerSingleton("myBean2", TestBean.class);
	wac.setServletContext(sc);
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	Properties props = new Properties();
	props.setProperty("key1", "value1");
	vr.setAttributes(props);
	Map<String, Object> map = new HashMap<>();
	map.put("key2", new Integer(2));
	vr.setAttributesMap(map);
	vr.setExposedContextBeanNames(new String[] {"myBean2"});
	vr.setApplicationContext(wac);

	MockHttpServletRequest request = new MockHttpServletRequest(sc) {
		@Override
		public RequestDispatcher getRequestDispatcher(String path) {
			return new MockRequestDispatcher(path) {
				@Override
				public void forward(ServletRequest forwardRequest, ServletResponse forwardResponse) {
					assertTrue("Correct rc attribute", forwardRequest.getAttribute("rc") == null);
					assertEquals("value1", forwardRequest.getAttribute("key1"));
					assertEquals(new Integer(2), forwardRequest.getAttribute("key2"));
					assertNull(forwardRequest.getAttribute("myBean"));
					assertSame(wac.getBean("myBean2"), forwardRequest.getAttribute("myBean2"));
				}
			};
		}
	};
	HttpServletResponse response = new MockHttpServletResponse();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
	View view = vr.resolveViewName("example1", Locale.getDefault());
	view.render(new HashMap<String, Object>(), request, response);
}
 
Example #24
Source File: Home.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  String nickname = userService.getCurrentUser().getNickname();
  String logoutUrl = userService.createLogoutURL(request.getRequestURI());

  request.setAttribute("nickname", nickname);
  request.setAttribute("logoutUrl", logoutUrl);
  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
  dispatcher.forward(request, response);
}
 
Example #25
Source File: DefaultWebApplication.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the request dispatcher.
 *
 * @param path the path.
 * @return the request dispatcher.
 */
@Override
public RequestDispatcher getRequestDispatcher(String path) {
    RequestDispatcher requestDispatcher = null;

    WebApplicationRequestMapping mapping = webApplicationRequestMapper.findServletMapping(path);
    if (mapping != null) {
        String servletName = webApplicationRequestMapper.getServletName(mapping.getPath());
        if (servletName != null) {
            requestDispatcher = getNamedDispatcher(servletName, path);
        }
    }

    return requestDispatcher;
}
 
Example #26
Source File: FibServletTests.java    From demo with MIT License 5 votes vote down vote up
/**
 * Here we allow a call into the actual forwardToResult method,
 * and we force an exception
 */
@Test
public void testPostService_realForward_withException() throws ServletException, IOException {
    FibServlet.logger = logger;
    final RequestDispatcher requestDispatcher = mock(RequestDispatcher.class);
    when(request.getRequestDispatcher(ServletUtils.RESTFUL_RESULT_JSP)).thenReturn(requestDispatcher);
    doThrow(new RuntimeException("hi there, exception here."))
            .when(requestDispatcher).forward(request, response);

    fibServlet.doPost(request, response);

    verify(request).getRequestDispatcher(ServletUtils.RESTFUL_RESULT_JSP);
    verify(FibServlet.logger).error(Mockito.anyString());
}
 
Example #27
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String getOriginalQueryString() {
    String uri = (String) getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
    if(uri != null) {
        return uri;
    }
    uri = (String) getAttribute(AsyncContext.ASYNC_QUERY_STRING);
    if(uri != null) {
        return uri;
    }
    return getQueryString();
}
 
Example #28
Source File: DefaultWrapperServlet.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Private
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
  RequestDispatcher rd = getServletContext().getNamedDispatcher("default");

  HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
    public String getServletPath() {
    return "";
    }
  };

  rd.forward(wrapped, resp);
  }
 
Example #29
Source File: RegisterServletTests.java    From demo with MIT License 5 votes vote down vote up
@Before
public void before() {
    request = mock(HttpServletRequest.class);
    response = mock(HttpServletResponse.class);
    requestDispatcher = mock(RequestDispatcher.class);
    registerServlet = spy(new RegisterServlet());
    RegisterServlet.registrationUtils = Mockito.mock(RegistrationUtils.class);
}
 
Example #30
Source File: PageContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private final String getAbsolutePathRelativeToContext(String relativeUrlPath) {
    String path = relativeUrlPath;

    if (!path.startsWith("/")) {
        String uri = (String) request.getAttribute(
                RequestDispatcher.INCLUDE_SERVLET_PATH);
        if (uri == null)
            uri = ((HttpServletRequest) request).getServletPath();
        String baseURI = uri.substring(0, uri.lastIndexOf('/'));
        path = baseURI + '/' + path;
    }

    return path;
}