请求转发和重定向

今天药忘吃喽~ 2023-07-21 06:05 377阅读 0赞

请求转发

A向B请求资源,B没有该资源,于是B向C请求该资源。C将资源返回给B,B将资源返回给A。

  1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2. // Attribute涉及servlet之间的传参
  3. request.setAttribute("name", "lsk");
  4. // 将请求传递给s2,s2是xml文件中设置的另一个servlet的<url-pattern>
  5. request.getRequestDispatcher("s2").forward(request, response);
  6. }
  7. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  8. String u_name = (String)request.getAttribute("name");
  9. response.getWriter().append("name:").append(u_name);
  10. }

特点:参数共享,一次请求,地址不变

20200402195228114.png

重定向

A向B请求资源,B没有该资源,B告诉A:C有你要的资源。于是A向C请求资源,C将资源返回给A。

  1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2. // 返回给请求方资源拥有者s2
  3. response.sendRedirect("s2");
  4. }
  5. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  6. String u_name = (String)request.getAttribute("name");
  7. response.getWriter().append("name:").append(u_name);
  8. }

特点:参数不共享,两次请求,地址变化 。url地址会由s1转到s2

2020040219521472.png

发表评论

表情:
评论列表 (有 0 条评论,377人围观)

还没有评论,来说两句吧...

相关阅读