鄙人初学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{
  
  }
}  

解决方案 »

  1.   

    这几句实现的功能是页面跳转,ServletContext是Servlet上下文
    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>
      

  2.   

    RequestDispatecher用于在servlet里转发或者是重定位,相当于jsp里的<jsp:forward>,<jsp:redirect>的作用。
      

  3.   

    谢谢两位的解答,我后来查到了文档.的确发现Servlet和Jsp有相同之处,可能Jsp更好用而且Jsp最终是要编译成Servlet才可以执行.以后还要遇到很多的问题咨询各位~~