在web开发中,转发与重定向有很大的区别。
直观看来,转发不会发生URL址的变换,而重定向则会发生URL的改变。
这仅仅只是一种表象。HttpServlet中的request对象和response对象是在用户请求网页时由服务器根据浏览器传过来的参数封装生成的。一旦从浏览器请求过来,服务器响应回去那么request和response的也就到了生命的终点了。
当使用转发的时候,浏览器仅仅请求一次但是服务器端可能经历了多次的跳转。服务器端执行时发生了转发那么服务器就停止正在执行的任务,去指定转发给定地址的任务。
而使用重定向的话,浏览器则会项服务器发生多次请求。在服务器端执行代码的时候,发现发生了重定向,那么它就会通知浏览器,去访问另一个URL。浏览器就会向被发送的URL请求资源。
看一段代码:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>login</title> </head> <body> <form action="myServlet" method="post"> name :<input type="text" name="username"/><br/> <input type="submit" value="submit"/> </form> </body> </html>
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
这是一段jsp代码,当点击提交的时候,会把表单提交给myServlet。
界面长这样:
public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = (String)request.getParameter("username");
request.setAttribute("welcome", "welcome!!!");
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
}
这是MySerlet,当用户点击提交表单,服务器就会调用MyServlet的doPost方法,在这个方法里面进行的是页面转发。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>welcome</title> </head> <body> <%=request.getParameter("username")%> <br/> <%=request.getAttribute("welcome") %> </body> </html>
这是welcome.jsp的代码。
提交结果为:
当点击提交按钮后后我们可以看一下网络的请求过程。
可以发现浏览器只向服务器发送了一个请求。
接下来看一下重定向。
如果把MyServlet的代码改一下。
public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = (String)request.getParameter("username");
request.setAttribute("welcome", "welcome!!!"); response.sendRedirect("welcome.jsp");
}
}
可以看到结果为:
而且浏览器项服务器发送了两次请求:
从上面的结果可以看出重定向后,因为是发起的另一个请求因此welcom页面中的内容都是null。而转发则由于是同一个request对象和response对象因此既能获得浏览器请求的参数,还能拿到request总放入的属性值。
其实从代码也可以看出来,sendRedirect()方法是HttpServletResponse对象的响应方法,既然调用了响应对象的方法,那么就表明整个请求结束了,服务器端项客户端返回执行结果。而getRequestDispatcher方法是request对象的方法,表明依旧在请求因此不会立即向浏览器返回结果,而是继续执行其转发的任务。
有一点需要说明的时,不论forward方法还是sendRedirect方法中传的URL需要注意,如果以“\”开头那么,就表示这个URL是现对于servlet容器根的请求,即localhost:8080,如果没有以“\”开头,那么表明这个请求地址是相对于当前的请求URL来寻址的。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>login</title> </head> <body> <form action="/myServlet" method="post"> name :<input type="text" name="username"/><br/> <input type="submit" value="submit"/> </form> </body> </html>
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
当我再次点击提交的时候:
不以”\”开头的请求地址为:
转发模型为:
重定向模型为:
蓝蓝设计( www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、 网站建设 、平面设计服务