java后端重定向
两个问题
- Servlet中,重定向之后的代码是否会继续执行?
- 重定向是在所有代码执行完毕后跳转,还是执行到重定向代码时立即跳转?
1.重定向之后的代码会继续执行
2.当前程序所有代码执行完毕后,才会执行重定向跳转
3.重定向之后,加上return,可让之后的代码不再执行
boolean flag = true;
if (flag) {
response.sendRedirect("url");
return;
}
要点:重定向和请求转发的区别
- 重定向是客户端行为,请求转发是服务器行为
- 重定向是response对象调用方法,请求转发是request对象调用方法
- 重定向是多次请求、多次响应,请求转发只有一次请求所以可以实现request域对象中的数据共享
- 重定向由服务端将重定向请求返回给客户端,再由客户端发起,而请求转发直接由服务器发起,效率要高于重定向
- 由于重定向客户端会出现两次请求访问,而请求转发是服务端行为,服务器直接转发,所以重定向效率较低
- 重定向地址栏会发生变化,请求转发url地址栏不变
- 重定向可以访问外部资源,而请求转发只能访问内部资源
后端重定向流程图:
后端重定向默认以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);
-
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgakfib
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13