首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

关于请求转发的有关问题。

2012-01-24 
关于请求转发的问题。。Java codepublic class CheckServlet extends HttpServlet {@Override//响应客服端请

关于请求转发的问题。。

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)

热点排行