下面列出了怎么用javax.servlet.RequestDispatcher的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
}
}
/**
* 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);
}
}
}
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();
}
}
/**
* 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;
}
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;
}
/**
* 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;
}
@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();
}
@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();
}
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);
}
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;
}
@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;
}
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);
}
/**
* 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));
}
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>");
}
}
@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;
}
}
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);
}
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);
}
}
@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"));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setAttribute(RequestDispatcher.ERROR_EXCEPTION,
new Throwable(ERROR_TEXT));
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
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);
}
}
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;
}
@Override
public RequestDispatcher getNamedDispatcher(String name) {
if (SecurityUtil.isPackageProtectionEnabled()) {
return (RequestDispatcher) doPrivileged("getNamedDispatcher",
new Object[]{name});
} else {
return context.getNamedDispatcher(name);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
// Skip filter if there isn't any selector in the URL
String selector = slingRequest.getRequestPathInfo().getSelectorString();
if (selector == null) {
chain.doFilter(request, response);
return;
}
// Skip filter on AEM author
WCMMode wcmMode = WCMMode.fromRequest(request);
if (!WCMMode.DISABLED.equals(wcmMode)) {
chain.doFilter(request, response);
return;
}
Resource page = slingRequest.getResource();
LOGGER.debug("Checking sub-pages for {}", slingRequest.getRequestURI());
Resource subPage = UrlProviderImpl.toSpecificPage(page, selector);
if (subPage != null) {
RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(subPage);
dispatcher.forward(slingRequest, response);
return;
}
chain.doFilter(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = request.getParameter("username");
String password = request.getParameter("password");
String path = "/failure.html";
if (username.equalsIgnoreCase("dilbert") && password.equals("password")) {
path = "/success.html";
}
RequestDispatcher rd = request.getRequestDispatcher(path);
rd.forward(request, response);
}
private void doForward(String relativeUrlPath) throws ServletException,
IOException {
// JSP.4.5 If the buffer was flushed, throw IllegalStateException
try {
out.clear();
baseOut.clear();
} catch (IOException ex) {
IllegalStateException ise = new IllegalStateException(Localizer
.getMessage("jsp.error.attempt_to_clear_flushed_buffer"));
ise.initCause(ex);
throw ise;
}
// Make sure that the response object is not the wrapper for include
while (response instanceof ServletResponseWrapperInclude) {
response = ((ServletResponseWrapperInclude) response).getResponse();
}
final String path = getAbsolutePathRelativeToContext(relativeUrlPath);
String includeUri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
if (includeUri != null)
request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
try {
context.getRequestDispatcher(path).forward(request, response);
} finally {
if (includeUri != null)
request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH,
includeUri);
}
}
@Test
public void getNamedDispatcherForDefaultServlet() throws Exception {
final String name = "default";
RequestDispatcher namedDispatcher = sc.getNamedDispatcher(name);
assertNotNull(namedDispatcher);
MockHttpServletResponse response = new MockHttpServletResponse();
namedDispatcher.forward(new MockHttpServletRequest(sc), response);
assertEquals(name, response.getForwardedUrl());
}
/**
* 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());
}
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();
}
/**
* Here we allow a call into the actual forwardToResult method,
* and we force an exception
*/
@Test
public void testPostService_realForward_withException() throws ServletException, IOException {
AckServlet.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);
ackServlet.doPost(request, response);
verify(request).getRequestDispatcher(ServletUtils.RESTFUL_RESULT_JSP);
verify(AckServlet.logger).error(Mockito.anyString());
}
/**
* 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);
}
}