【JavaWeb】Response请求转发与重定向辨析
生活随笔
收集整理的這篇文章主要介紹了
【JavaWeb】Response请求转发与重定向辨析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
請求轉發與重定向對比
辨析
請求轉發只有一次請求、一次響應,是在服務端內部跳轉
重定向有兩次請求、兩次響應:將結果返回給客戶端,讓客戶端重新發起一次跳轉
請求轉發的登陸界面實現
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body><form action="check.jsp" method="post">用戶名:答案zs<input type="text" name="uname"><br/>密碼:答案abc<input type="password" name="upwd"><br/>愛好:<input type="textpassword" name="uhobby"><br/><input type="submit" value="登陸"><br/></form> </body> </html>check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body><%request.setCharacterEncoding("utf-8");String name = request.getParameter("uname");String pwd = request.getParameter("upwd");if (name.equals("zs") && pwd.equals("abc")) {//假設 zs abc//response.sendRedirect("success.jsp");//頁面跳轉:重定向, 導致數據丟失//頁面跳轉:請求轉發, 可以獲取到數據,并且 地址欄 沒有改變(仍然保留 轉發時的頁面check.jsp)request.getRequestDispatcher("success.jsp").forward(request,response);} else {//登陸失敗out.print("用戶名或密碼有誤!");}%> </body> </html>success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body><br>登錄成功。你好,<%String name = request.getParameter("uname");String password = request.getParameter("upwd");String hobby = request.getParameter("uhobby");out.print(name);%><br>你的用戶名是:<%=name%><br>你的密碼是:<%=password%><br>你的愛好是:<%=hobby%></body> </html>效果
可以看到頁面不跳轉到success.jsp
總結
以上是生活随笔為你收集整理的【JavaWeb】Response请求转发与重定向辨析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【GitHub教程】如何使用Eclips
- 下一篇: 【Java爬虫】我的第一个爬虫 -- 简