#转发和重定向的区别
##当客户端请求到了某个Servlet类之后,Servlet类进行处理,但是并不使用这个Servlet来响应客户端,而是要使用另一个Servlet来响应。
转发
- 转发是在服务器端,两个Servlet之间的请求行为
- 浏览器只对服务器进行了一次请求
- 浏览器的地址不会改变,浏览器请求ServletA,ServletA转到ServletB由ServletB响应浏览器,浏览器显示的是ServletA的访问地址
- 转发过程中,可以通过request对象传递数据
示例:
ServletA 转发到 ServletB
1. 数据传递
- ServletA 转发到 ServletB,并传递参数
***- ServletA传数据***
```java
- @WebServlet("/a")
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("AServlete-------------");
//给请求添加参数和值
req.setAttribute("servleta", "Servlet A");
//把请求request转发到BServlet
req.getRequestDispatcher("/c").forward(req, resp);
}
}
*- **ServletB取数据***
```java
- `@WebServlet("/b")
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Param: " + req.getAttribute("servleta"));
System.out.println("BServlet-----------");
resp.setStatus(200);
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
resp.getWriter().write("<h1>Hello BServlet</h1>");
}
}
重定向
- 客户端请求ServletA,ServletA响应给客户端一个新的请求地址ServletB,让客户端重新向ServeltB发送请求。
- 重定向是客户端的行为
- 浏览器对服务器发送了两次请求;
- 重定向是由浏览器再次发送请求,浏览器地址会改变为转发的地址;
- 不能通过request对象将ServletA中的数据传递给ServletB
- 重定向代码实现
@WebServlet("/a")
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("AServlete-------------");
//给请求添加参数和值
req.setAttribute("servleta", "Servlet A");
//把请求重定向到BServlet
resp.sendRedirect("/b");
}
}
```1. 数据不能通过request对象传递
```java
@WebServlet("/b")
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Param: " + req.getAttribute("servleta"));
System.out.println("BServlet-----------");
resp.setStatus(200);
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
resp.getWriter().write("<h1>Hello BServlet</h1>");
}
}