日期:2014-05-17  浏览次数:20799 次

关于请求转发的问题。。
Java code
public class CheckServlet extends HttpServlet {
  @Override
  //响应客服端请求
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    //获取用户名
    String username = request.getParameter("username");
    String message = null;
    if(username==null)
      message = "please input username";
    else {
      message = "hello "+username;
    }
    
    //添加message属性
    request.setAttribute("message", message);
    
    //把请求转发给outputServlet
    ServletContext context = getServletContext();
    RequestDispatcher dispatcher = context.getNamedDispatcher("/output");
    
    PrintWriter out = response.getWriter();
    out.print("output from checkServlet before forwarding request");
    System.out.println("output from checkServlet before forwarding request");
    dispatcher.forward(request,response);
    
    out.print("output from checkServlet after forwarding request");
    System.out.println("output from checkServlet after forwarding request");
  }  
}

这段代码是将相关的信息转发到OutputServlet中去:OutputServlet中的代码如下
Java code
public class OutServlet extends HttpServlet {

  @Override

  public void service(ServletRequest request, ServletResponse response)

      throws ServletException, IOException {

    //读取checkServlet存放在请求范围内的消息

    String message = (String) request.getAttribute("message");

    PrintWriter out = response.getWriter();

    out.print(message);

    out.close();

  }

}


所有的配置都是没有问题的。但是对于dispatcher.forward(request,response);这个代码就会抛出NullPointerException异常
为什么呢???



------解决方案--------------------
RequestDispatcher dispatcher = request.getRequestDispatcher("/output");
------解决方案--------------------
楼主试试 request.getRequestDispatcher("/output").forward(request, response)