您的位置:首页 > 产品设计 > UI/UE

request对象请求转发小例子笔记

2020-02-17 05:25 176 查看

请求转发:一种在服务器内部资源跳转的方式。
步骤
1.通过requeest对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)。
2.使用这个对象来进行转发:forward(ServletRequest request , ServletResponse response)。
小例子:

@WebServlet("/RequestDemo8")
public class RequestDemo8 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo8被访问了。。");
//转发到demo9资源
/*RequestDispatcher requestDispatcher = request.getRequestDispatcher("/RequestDemo9");
requestDispatcher.forward(request,response);*/
//推荐使用的方法
request.getRequestDispatcher("/RequestDemo9").forward(request,response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
@WebServlet("/RequestDemo9")
public class RequestDemo9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo9被访问了。。");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}

控制台输出

特点:
1.浏览器地址栏路径不发生变化。
2.只能转发到当前服务器内部资源中。
3.即使转发多个资源路径,也只向服务器请求一次,是最开始的那次。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
凉凉 发布了12 篇原创文章 · 获赞 0 · 访问量 85 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: