来自于:http://blog.csdn.net/xiangxiaofeng12/article/details/5564756
String path="/index.jsp";//这是当前应用中一个绝对路径的url
servlet:
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(path);
jsp:
RequestDispatcher dispatcher=application.getRequestDispatcher(path);
all:
dispatcher.forward();//转到path这个页面(不可以在这之前或之后有其它输出)
dispatcher.include();//向浏览器输出path这个页面的执行结果(可以在这之前或之后有其它输出)
1、ServletRequest.getRequestDispatcher(String path)
path可是绝对路径也可以是相对路径
2、ServletContext.getRequestDispatcher(String path)
path必须以"/"开头,代表context root
3、另一个方法 ServletContext.getNameDispatcher(String name)
参数并不是路径,而是其名称,如果有多个Servlet名称一样的,在web.xml进行配置区别
4、以上方法回传一个RequestDispatcher对象,接着forward()或include()
5、forward()和include()区别在于include()方法将HTTP请求转送给其他Servlet或jsp后,这个Servlet或jsp虽然可以处理请求,但是主导权还是原来的Servlet或jsp,就是被调用的Servlet或jsp如果产生任何HTTP回应,将会并入原来的HttpResponse对象
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage=""%> <%@ page import="java.net.URLEncoder"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>下载</title> </head> <body> <% response.setContentType("application/x-download"); String fileDownload = "/bgqb_radio_select.png"; String filedisplay = "bgqb_radio_select.png"; response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filedisplay, "UTF-8")); try { RequestDispatcher dis = application .getRequestDispatcher(fileDownload); if (dis != null) { dis.forward(request, response); } response.flushBuffer(); out.clear(); out = pageContext.pushBody(); } catch (Exception e) { e.printStackTrace(); } %> </body> </html>
void downLoaded(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/x-download;charset=UTF-8"); // response.setContentType("application/octet-stream;charset=UTF-8"); ServletOutputStream outputStream = response.getOutputStream(); BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream(fileName)); int size = 2048; byte[] data = new byte[size]; while ((size = inputStream.read(data, 0, data.length)) != 0) { outputStream.write(data, 0, size); outputStream.flush(); } }
补充:
问题getOutputStream() has already been called for this response,详见: