鄙人初学JAVA Web,在一个Servlet中不知道RequestDispatcher为何类,有哪些方法(见程序的最后部分).由于没有下载API文档,也查不到,希望各位帮忙.给出下列代码:
package mypack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class DispatcherServlet extends HttpServlet{
private String target="/hello.jsp";
public void init(ServletConfig config)
throws ServetException{
super.init(config);
}public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
public void doPost(HttpServeltRequest request,
HttpServletResponse response)
throws ServletException,IOException{
String username=request.getParameter("username");
String password=request.getParameter("password");
request.setAttribute("USER",username);
request.setAttribute("PASSWORD",password);
ServletContext context=getServletContext();/**从这里开始
System.out.println("Redirecting to"+target);
RequestDispatecher dispatcher=
context.getRequestDispatcher(target);
dispatcher.forward(request.response); 一直到这里*/
}
public void destroy{
}
}
package mypack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class DispatcherServlet extends HttpServlet{
private String target="/hello.jsp";
public void init(ServletConfig config)
throws ServetException{
super.init(config);
}public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
public void doPost(HttpServeltRequest request,
HttpServletResponse response)
throws ServletException,IOException{
String username=request.getParameter("username");
String password=request.getParameter("password");
request.setAttribute("USER",username);
request.setAttribute("PASSWORD",password);
ServletContext context=getServletContext();/**从这里开始
System.out.println("Redirecting to"+target);
RequestDispatecher dispatcher=
context.getRequestDispatcher(target);
dispatcher.forward(request.response); 一直到这里*/
}
public void destroy{
}
}
ServletContext context=getServletContext();
这句准确的应该是这样
ServletContext context=this.getServletContext();
也就是用HttpServlet中的方法getServletContext()来获取ServletContext对象
再由ServletContext中的方法getRequestDispatcher(String path)[你的程序里是"/hello.jsp"]获得RequestDispatecher对象,这个对象在你的程序里包含了"/hello.jsp"这个路径,最后一步就是实现转发了,在web中页面跳到hello.jsp这个页面这段程序相当于JSP中的标签<jsp:forward>