idea创建简单web项目分析Servlet的请求转发与重定向的区别

 注:如需转载,请附上原文链接,如有建议或意见,欢迎批评指正!

需求说明:

// index.jsp页面
 1 <%
 2   String basePath = request.getScheme()+":"+"//"+request.getServerName()+":"+request.getServerPort()+"/"
 3           +request.getServletContext().getContextPath()+"/";
 4 %>
 5 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 6 <html>
 7   <head>
 8     <title>ServletDemo加法运算</title>
 9   </head>
10   <body>
11     <%--action: 表示访问的servlet路径--%>
12     <%out.print("basePath意味着:" + basePath);%>
13     <form action="<%=basePath%>ServletDemo1" method="post">
14       a: <input type="text" name="a"><br>
15       b: <input type="text" name="b"><br>
16       <input type="submit" value="计算"/><br>
17     </form>
18   </body>
19 </html>
// ServletDemo1.java
 1 import javax.servlet.ServletContext;
 2 import javax.servlet.ServletException;
 3 import javax.servlet.annotation.WebServlet;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import java.io.IOException;
 8 
 9 @WebServlet("/ServletDemo1")
10 public class ServletDemo1 extends HttpServlet {
11     @Override
12     public void init() throws ServletException {
13         System.out.println("init()方法");
14     }
15 
16     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         System.out.println("doPost()方法");
18         doGet(request, response);
19     }
20 
21     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
22         String a = request.getParameter("a");
23         String b = request.getParameter("b");
24         int sum = Integer.valueOf(a) + Integer.valueOf(b);
25         request.setAttribute("sum", sum);
26         // 方式一:PrintWriter对象写入
27 //        response.getWriter().print(sum);
28         // 方式二:请求转发
29 //        request.getRequestDispatcher("sum.jsp").forward(request, response);
30         // 方式三:重定向
31         ServletContext sc = request.getServletContext();
32         sc.setAttribute("sum2", sum);
33         response.sendRedirect("sum2.jsp");
34         System.out.println("doGet()方法");
35     }
36 
37     @Override
38     public void destroy() {
39         System.out.println("destroy()方法");
40     }
41 }

// sum.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求跳转求和</title>
</head>
<body>
a + b = <%=request.getAttribute("sum")%>
</body>
</html>

// sum2.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>重定向跳转求和</title>
</head>
<body>
a + b = <%=application.getAttribute("sum2")%>
</body>
</html>

index.jsp页面效果图展示:

1. 方式一:PrintWriter对象写入效果图:

 

2. 方式二:请求转发效果图:

 

 

3. 重定向效果图:

 

posted @ 2018-04-29 10:24  Chris_Lee  阅读(684)  评论(0编辑  收藏  举报