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

时间:2021-07-05 15:26:02
 注:如需转载,请附上原文链接,如有建议或意见,欢迎批评指正!

需求说明:

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
 import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @WebServlet("/ServletDemo1")
public class ServletDemo1 extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("init()方法");
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost()方法");
doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
String b = request.getParameter("b");
int sum = Integer.valueOf(a) + Integer.valueOf(b);
request.setAttribute("sum", sum);
// 方式一:PrintWriter对象写入
// response.getWriter().print(sum);
// 方式二:请求转发
// request.getRequestDispatcher("sum.jsp").forward(request, response);
// 方式三:重定向
ServletContext sc = request.getServletContext();
sc.setAttribute("sum2", sum);
response.sendRedirect("sum2.jsp");
System.out.println("doGet()方法");
} @Override
public void destroy() {
System.out.println("destroy()方法");
}
} // 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页面效果图展示:

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

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

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

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

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

3. 重定向效果图:

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