关于java后端重定向

两个问题

  1. Servlet中,重定向之后的代码是否会继续执行?
  2. 重定向是在所有代码执行完毕后跳转,还是执行到重定向代码时立即跳转?

1.重定向之后的代码会继续执行

2.当前程序所有代码执行完毕后,才会执行重定向跳转

3.重定向之后,加上return,可让之后的代码不再执行

boolean flag = true;
if (flag) {
    response.sendRedirect("url");
    return;
}

要点:重定向和请求转发的区别

  1. 重定向是客户端行为,请求转发是服务器行为
  2. 重定向是response对象调用方法,请求转发是request对象调用方法
  3. 重定向是多次请求、多次响应,请求转发只有一次请求所以可以实现request域对象中的数据共享
  4. 重定向由服务端将重定向请求返回给客户端,再由客户端发起,而请求转发直接由服务器发起,效率要高于重定向
  5. 由于重定向客户端会出现两次请求访问,而请求转发是服务端行为,服务器直接转发,所以重定向效率较低
  6. 重定向地址栏会发生变化,请求转发url地址栏不变
  7. 重定向可以访问外部资源,而请求转发只能访问内部资源

后端重定向流程图:

后端重定向默认以get方式

后端使用post方式重定向

public class RedirectWithPost {
  Map<String, String> parameter = new HashMap<String, String>();
  HttpServletResponse response;
  
  public RedirectWithPost(HttpServletResponse response) {
    this.response = response;
  }
  
  public void setParameter(String key, String value) {
    this.parameter.put(key, value);
  }
  
  public void sendByPost(String url) throws IOException {
    this.response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = this.response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println(" <HEAD>");
    out.println(" <meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
    out.println(" <TITLE>loading</TITLE>");
    out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html charset=GBK\">\n");
    out.println(" </HEAD>");
    out.println(" <BODY>");
    out.println("<form name=\"submitForm\" action=\"" + url + "\" method=\"post\">");
    Iterator<String> it = this.parameter.keySet().iterator();
    while (it.hasNext()) {
      String key = it.next();
      out.println("<input type=\"hidden\" name=\"" + key + "\" value=\"" + this.parameter.get(key) + "\"/>");
    }
    out.println("</from>");
    out.println("<script>window.document.submitForm.submit();</script> ");
    out.println(" </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
  }
}

后端post重定向

   private  void loginTokenApi(HttpServletResponse httpServletResponse, String username, String password) throws IOException, ServletException {
        RedirectWithPost redirectWithPost = new RedirectWithPost(httpServletResponse);
        //redirectUrl请求地址
        String redirectUrl = "/loginRecordApi";
        redirectWithPost.setParameter("username", username);
        redirectWithPost.setParameter("password", password);
        redirectWithPost.sendByPost(redirectUrl);
    }

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值