本文整理汇总了Java中javax.servlet.ServletContext.getRequestDispatcher方法的典型用法代码示例。如果您正苦于以下问题:Java ServletContext.getRequestDispatcher方法的具体用法?Java ServletContext.getRequestDispatcher怎么用?Java ServletContext.getRequestDispatcher使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.servlet.ServletContext
的用法示例。
在下文中一共展示了ServletContext.getRequestDispatcher方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processHTTPRequest
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* This method handles the HTTP request for the user token resolution. It
* calls the <code>resolveUsertoken</code> method. After the token has been
* resolved, it forwards the request to the target path configured in the
* <code>TOKENHANDLER_FORWARD</code> property.
*
* @param request
* the HTTP servlet request with the user token to be resolved
* @param response
* the HTTP servlet response for the request
* @param servletContext
* the servlet context of the request
* @throws ServletException
* if the forwarding of the request or the call to the platform
* fails
* @throws IOException
* if the forwarding of the request fails
*/
static public void processHTTPRequest(HttpServletRequest request,
HttpServletResponse response, ServletContext servletContext)
throws ServletException, IOException {
String usertoken = request.getParameter(Constants.USERTOKEN);
String instanceId = request.getParameter(Constants.INSTANCE_ID);
String bssId = request.getParameter(Constants.CM_ID);
String subKey = request.getParameter(Constants.SUB_KEY);
String userId = BssClient.resolveUsertoken(request.getSession(),
usertoken, instanceId, subKey, bssId);
if (userId == null || userId.length() == 0) {
logger.error("Error: missing userId!");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
String forward = wsProxyInfo.getForward();
logger.debug("Forward to " + forward);
RequestDispatcher rd = servletContext.getRequestDispatcher(forward);
rd.forward(request, response);
}
示例2: perform
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* Method associated to a tile and called immediately before the tile
* is included. This implementation calls an <code>Action</code>.
* No servlet is set by this method.
*
* @param tileContext Current tile context.
* @param request Current request.
* @param response Current response.
* @param servletContext Current servlet context.
*/
public void perform(
ComponentContext tileContext,
HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext)
throws ServletException, IOException {
RequestDispatcher rd = servletContext.getRequestDispatcher(url);
if (rd == null) {
throw new ServletException(
"Controller can't find url '" + url + "'.");
}
rd.include(request, response);
}
示例3: execute
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* @see org.apache.struts.tiles.Controller#execute(org.apache.struts.tiles.ComponentContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.ServletContext)
*/
public void execute(
ComponentContext tileContext,
HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext)
throws Exception {
RequestDispatcher rd = servletContext.getRequestDispatcher(url);
if (rd == null) {
throw new ServletException(
"Controller can't find url '" + url + "'.");
}
rd.include(request, response);
}
示例4: custom
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* Handle an HTTP status code or Java exception by forwarding control
* to the location included in the specified errorPage object. It is
* assumed that the caller has already recorded any request attributes
* that are to be forwarded to this page. Return <code>true</code> if
* we successfully utilized the specified error page location, or
* <code>false</code> if the default error report should be rendered.
*
* @param request The request being processed
* @param response The response being generated
* @param errorPage The errorPage directive we are obeying
*/
protected boolean custom(Request request, Response response,
ErrorPage errorPage) {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("Processing " + errorPage);
request.setPathInfo(errorPage.getLocation());
try {
// Reset the response (keeping the real error code and message)
response.resetBuffer(true);
// Forward control to the specified location
ServletContext servletContext =
request.getContext().getServletContext();
RequestDispatcher rd =
servletContext.getRequestDispatcher(errorPage.getLocation());
rd.forward(request.getRequest(), response.getResponse());
// If we forward, the response is suspended again
response.setSuspended(false);
// Indicate that we have successfully processed this custom page
return (true);
} catch (Throwable t) {
// Report our failure to process this custom page
container.getLogger().error("Exception Processing " + errorPage, t);
return (false);
}
}
示例5: custom
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* Handle an HTTP status code or Java exception by forwarding control
* to the location included in the specified errorPage object. It is
* assumed that the caller has already recorded any request attributes
* that are to be forwarded to this page. Return <code>true</code> if
* we successfully utilized the specified error page location, or
* <code>false</code> if the default error report should be rendered.
*
* @param request The request being processed
* @param response The response being generated
* @param errorPage The errorPage directive we are obeying
*/
protected boolean custom(Request request, Response response,
ErrorPage errorPage) {
if (debug >= 1)
log("Processing " + errorPage);
// Validate our current environment
if (!(request instanceof HttpRequest)) {
if (debug >= 1)
log(" Not processing an HTTP request --> default handling");
return (false); // NOTE - Nothing we can do generically
}
HttpServletRequest hreq =
(HttpServletRequest) request.getRequest();
if (!(response instanceof HttpResponse)) {
if (debug >= 1)
log("Not processing an HTTP response --> default handling");
return (false); // NOTE - Nothing we can do generically
}
HttpServletResponse hres =
(HttpServletResponse) response.getResponse();
try {
// Reset the response if possible (else IllegalStateException)
hres.reset();
// Forward control to the specified location
ServletContext servletContext =
request.getContext().getServletContext();
RequestDispatcher rd =
servletContext.getRequestDispatcher(errorPage.getLocation());
rd.forward(hreq, hres);
// If we forward, the response is suspended again
response.setSuspended(false);
// Indicate that we have successfully processed this custom page
return (true);
} catch (Throwable t) {
// Report our failure to process this custom page
log("Exception Processing " + errorPage, t);
return (false);
}
}
示例6: getFileText
import javax.servlet.ServletContext; //导入方法依赖的package包/类
public String getFileText( String originalPath, boolean virtual ) throws IOException {
try {
ServletContextAndPath csAndP = getServletContextAndPath( originalPath, virtual );
ServletContext context = csAndP.getServletContext();
String path = csAndP.getPath();
RequestDispatcher rd =
context.getRequestDispatcher( path );
if ( rd == null ) {
throw new IOException("Couldn't get request dispatcher for path: " + path );
}
ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
ResponseIncludeWrapper responseIncludeWrapper =
new ResponseIncludeWrapper(res, basos );
rd.include(req, responseIncludeWrapper );
//We can't assume the included servlet flushed its output
responseIncludeWrapper.flushOutputStreamOrWriter();
byte[] bytes = basos.toByteArray();
//Assume that the default encoding is what was used to encode the bytes. Questionable.
String retVal = new String( bytes );
//make an assumption that an empty response is a failure. This is a problem if a truly empty file
//were included, but not sure how else to tell.
if ( retVal.equals("") ) {
throw new IOException("Couldn't find file: " + path );
}
return retVal;
} catch (ServletException e) {
throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage() );
}
}
示例7: buildSurveyHtml
import javax.servlet.ServletContext; //导入方法依赖的package包/类
private void buildSurveyHtml() throws Exception{
HttpServletRequest request=Struts2Utils.getRequest();
HttpServletResponse response=Struts2Utils.getResponse();
String url = "";
String name = "";
ServletContext sc = ServletActionContext.getServletContext();
String file_name = request.getParameter("file_name");
url = "/design/my-collect.action?surveyId=402880ea4675ac62014675ac7b3a0000";
// 这是生成的html文件名,如index.htm.
name = "/survey.htm";
name = sc.getRealPath(name);
RequestDispatcher rd = sc.getRequestDispatcher(url);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final ServletOutputStream stream = new ServletOutputStream() {
public void write(byte[] data, int offset, int length) {
os.write(data, offset, length);
}
public void write(int b) throws IOException {
os.write(b);
}
};
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,"utf-8"));
HttpServletResponse rep = new HttpServletResponseWrapper(response) {
public ServletOutputStream getOutputStream() {
return stream;
}
public PrintWriter getWriter() {
return pw;
}
};
// rd.include(request, rep);
rd.forward(request,rep);
pw.flush();
// 把jsp输出的内容写到xxx.htm
File file = new File(name);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
os.writeTo(fos);
fos.close();
}
示例8: jspWriteToHtml
import javax.servlet.ServletContext; //导入方法依赖的package包/类
public void jspWriteToHtml(String url, String filePath,String fileName) throws Exception {
HttpServletRequest request = Struts2Utils.getRequest();
HttpServletResponse response = Struts2Utils.getResponse();
ServletContext sc = ServletActionContext.getServletContext();
url = "/my-survey-design!previewDev.action?surveyId=402880ea4675ac62014675ac7b3a0000";
// 这是生成的html文件名,如index.htm
filePath = filePath.replace("/", File.separator);
filePath = filePath.replace("\\", File.separator);
String fileRealPath = sc.getRealPath("/") + filePath;
RequestDispatcher rd = sc.getRequestDispatcher(url);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final ServletOutputStream stream = new ServletOutputStream() {
public void write(byte[] data, int offset, int length) {
os.write(data, offset, length);
}
public void write(int b) throws IOException {
os.write(b);
}
};
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,
"UTF-8"));
HttpServletResponse rep = new HttpServletResponseWrapper(response) {
public ServletOutputStream getOutputStream() {
return stream;
}
public PrintWriter getWriter() {
return pw;
}
};
rd.forward(request, response);
pw.flush();
File file2 = new File(fileRealPath);
if (!file2.exists() || !file2.isDirectory()) {
file2.mkdirs();
}
File file = new File(fileRealPath + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
os.writeTo(fos);
fos.close();
}
示例9: getFileText
import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public String getFileText(String originalPath, boolean virtual) throws IOException {
try {
ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual);
ServletContext context = csAndP.getServletContext();
String path = csAndP.getPath();
RequestDispatcher rd = context.getRequestDispatcher(path);
if (rd == null) {
throw new IOException("Couldn't get request dispatcher for path: " + path);
}
ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(context, req, res, basos);
rd.include(req, responseIncludeWrapper);
// We can't assume the included servlet flushed its output
responseIncludeWrapper.flushOutputStreamOrWriter();
byte[] bytes = basos.toByteArray();
// Assume platform default encoding unless otherwise specified
String retVal;
if (inputEncoding == null) {
retVal = new String(bytes);
} else {
retVal = new String(bytes, B2CConverter.getCharset(inputEncoding));
}
// make an assumption that an empty response is a failure. This is
// a problem
// if a truly empty file
// were included, but not sure how else to tell.
if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(org.apache.coyote.http11.Constants.HEAD)) {
throw new IOException("Couldn't find file: " + path);
}
return retVal;
} catch (ServletException e) {
throw new IOException(
"Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage());
}
}
示例10: getFileText
import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public String getFileText(String originalPath, boolean virtual)
throws IOException {
try {
ServletContextAndPath csAndP = getServletContextAndPath(
originalPath, virtual);
ServletContext context = csAndP.getServletContext();
String path = csAndP.getPath();
RequestDispatcher rd = context.getRequestDispatcher(path);
if (rd == null) {
throw new IOException(
"Couldn't get request dispatcher for path: " + path);
}
ByteArrayServletOutputStream basos =
new ByteArrayServletOutputStream();
ResponseIncludeWrapper responseIncludeWrapper =
new ResponseIncludeWrapper(context, req, res, basos);
rd.include(req, responseIncludeWrapper);
//We can't assume the included servlet flushed its output
responseIncludeWrapper.flushOutputStreamOrWriter();
byte[] bytes = basos.toByteArray();
//Assume platform default encoding unless otherwise specified
String retVal;
if (inputEncoding == null) {
retVal = new String( bytes );
} else {
retVal = new String (bytes,
B2CConverter.getCharset(inputEncoding));
}
//make an assumption that an empty response is a failure. This is
// a problem
// if a truly empty file
//were included, but not sure how else to tell.
if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(
org.apache.coyote.http11.Constants.HEAD)) {
throw new IOException("Couldn't find file: " + path);
}
return retVal;
} catch (ServletException e) {
throw new IOException("Couldn't include file: " + originalPath
+ " because of ServletException: " + e.getMessage());
}
}
示例11: custom
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* Handle an HTTP status code or Java exception by forwarding control
* to the location included in the specified errorPage object. It is
* assumed that the caller has already recorded any request attributes
* that are to be forwarded to this page. Return <code>true</code> if
* we successfully utilized the specified error page location, or
* <code>false</code> if the default error report should be rendered.
*
* @param request The request being processed
* @param response The response being generated
* @param errorPage The errorPage directive we are obeying
*/
private boolean custom(Request request, Response response,
ErrorPage errorPage) {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("Processing " + errorPage);
try {
// Forward control to the specified location
ServletContext servletContext =
request.getContext().getServletContext();
RequestDispatcher rd =
servletContext.getRequestDispatcher(errorPage.getLocation());
if (rd == null) {
container.getLogger().error(
sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation()));
return false;
}
if (response.isCommitted()) {
// Response is committed - including the error page is the
// best we can do
rd.include(request.getRequest(), response.getResponse());
} else {
// Reset the response (keeping the real error code and message)
response.resetBuffer(true);
response.setContentLength(-1);
rd.forward(request.getRequest(), response.getResponse());
// If we forward, the response is suspended again
response.setSuspended(false);
}
// Indicate that we have successfully processed this custom page
return (true);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// Report our failure to process this custom page
container.getLogger().error("Exception Processing " + errorPage, t);
return (false);
}
}
示例12: dispatch
import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public void dispatch(ServletContext context, String path) {
synchronized (asyncContextLock) {
if (log.isDebugEnabled()) {
logDebug("dispatch ");
}
check();
if (dispatch != null) {
throw new IllegalStateException(
sm.getString("asyncContextImpl.dispatchingStarted"));
}
if (request.getAttribute(ASYNC_REQUEST_URI)==null) {
request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI());
request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath());
request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath());
request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo());
request.setAttribute(ASYNC_QUERY_STRING, request.getQueryString());
}
final RequestDispatcher requestDispatcher = context.getRequestDispatcher(path);
if (!(requestDispatcher instanceof AsyncDispatcher)) {
throw new UnsupportedOperationException(
sm.getString("asyncContextImpl.noAsyncDispatcher"));
}
final AsyncDispatcher applicationDispatcher =
(AsyncDispatcher) requestDispatcher;
final ServletRequest servletRequest = getRequest();
final ServletResponse servletResponse = getResponse();
Runnable run = new Runnable() {
@Override
public void run() {
request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null);
try {
applicationDispatcher.dispatch(servletRequest, servletResponse);
}catch (Exception x) {
//log.error("Async.dispatch",x);
throw new RuntimeException(x);
}
}
};
this.dispatch = run;
this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null);
clearServletRequestResponse();
}
}
示例13: getFileText
import javax.servlet.ServletContext; //导入方法依赖的package包/类
public String getFileText(String originalPath, boolean virtual)
throws IOException {
try {
ServletContextAndPath csAndP = getServletContextAndPath(
originalPath, virtual);
ServletContext context = csAndP.getServletContext();
String path = csAndP.getPath();
RequestDispatcher rd = context.getRequestDispatcher(path);
if (rd == null) {
throw new IOException(
"Couldn't get request dispatcher for path: " + path);
}
ByteArrayServletOutputStream basos =
new ByteArrayServletOutputStream();
ResponseIncludeWrapper responseIncludeWrapper =
new ResponseIncludeWrapper(context, req, res, basos);
rd.include(req, responseIncludeWrapper);
//We can't assume the included servlet flushed its output
responseIncludeWrapper.flushOutputStreamOrWriter();
byte[] bytes = basos.toByteArray();
//Assume platform default encoding unless otherwise specified
String retVal;
if (inputEncoding == null) {
retVal = new String( bytes );
} else {
retVal = new String (bytes, inputEncoding);
}
//make an assumption that an empty response is a failure. This is
// a problem
// if a truly empty file
//were included, but not sure how else to tell.
if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(
org.apache.coyote.http11.Constants.HEAD)) {
throw new IOException("Couldn't find file: " + path);
}
return retVal;
} catch (ServletException e) {
throw new IOException("Couldn't include file: " + originalPath
+ " because of ServletException: " + e.getMessage());
}
}
示例14: doInterpret
import javax.servlet.ServletContext; //导入方法依赖的package包/类
private void doInterpret(String requestURL,Map<String, Object> variables, OutputStream output) throws IOException, ServletException {
/**
* 创建ServletContext对象,用于获取RequestDispatcher对象
*/
ServletContext sc = request.getSession().getServletContext();
/**
* 根据传过来的相对文件路径,生成一个reqeustDispatcher的包装类
*/
RequestDispatcher rd = sc.getRequestDispatcher(requestURL);
/**
* 创建一个ByteArrayOutputStream的字节数组输出流,用来存放输出的信息
*/
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
/**
* ServletOutputStream是抽象类,必须实现write的方法
*/
final ServletOutputStream outputStream = new ServletOutputStream(){
public void write(int b) throws IOException {
/**
* 将指定的字节写入此字节输出流
*/
baos.write(b);
}
@SuppressWarnings("unused")
public boolean isReady() {
return false;
}
};
/**
* 通过现有的 OutputStream 创建新的 PrintWriter
* OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节
*/
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, config.getOutputEncoding() ),true);
/**
* 生成HttpServletResponse的适配器,用来包装response
*/
HttpServletResponse resp = new HttpServletResponseWrapper(response){
/**
* 调用getOutputStream的方法(此方法是ServletResponse中已有的)返回ServletOutputStream的对象
* 用来在response中返回一个二进制输出对象
* 此方法目的是把源文件写入byteArrayOutputStream
*/
public ServletOutputStream getOutputStream(){
return outputStream;
}
/**
* 再调用getWriter的方法(此方法是ServletResponse中已有)返回PrintWriter的对象
* 此方法用来发送字符文本到客户端
*/
public PrintWriter getWriter(){
return pw;
}
};
/**
* 在不跳转下访问目标jsp。 就是利用RequestDispatcher.include(ServletRequest request,
* ServletResponse response)。 该方法把RequestDispatcher指向的目标页面写到response中。
*/
rd.include(request, resp);
pw.flush();
/**
* 使用ByteArrayOutputStream的writeTo方法来向文本输出流写入数据,这也是为什么要使用ByteArray的一个原因
*/
baos.writeTo(output);
}
示例15: custom
import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
* Handle an HTTP status code or Java exception by forwarding control to the
* location included in the specified errorPage object. It is assumed that
* the caller has already recorded any request attributes that are to be
* forwarded to this page. Return <code>true</code> if we successfully
* utilized the specified error page location, or <code>false</code> if the
* default error report should be rendered.
*
* @param request
* The request being processed
* @param response
* The response being generated
* @param errorPage
* The errorPage directive we are obeying
*/
private boolean custom(Request request, Response response, ErrorPage errorPage) {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("Processing " + errorPage);
try {
// Forward control to the specified location
ServletContext servletContext = request.getContext().getServletContext();
RequestDispatcher rd = servletContext.getRequestDispatcher(errorPage.getLocation());
if (rd == null) {
container.getLogger()
.error(sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation()));
return false;
}
if (response.isCommitted()) {
// Response is committed - including the error page is the
// best we can do
rd.include(request.getRequest(), response.getResponse());
} else {
// Reset the response (keeping the real error code and message)
response.resetBuffer(true);
response.setContentLength(-1);
rd.forward(request.getRequest(), response.getResponse());
// If we forward, the response is suspended again
response.setSuspended(false);
}
// Indicate that we have successfully processed this custom page
return (true);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// Report our failure to process this custom page
container.getLogger().error("Exception Processing " + errorPage, t);
return (false);
}
}