idea创建简单web项目分析Servlet的请求转发与重定向的区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了idea创建简单web项目分析Servlet的请求转发与重定向的区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2814字,纯文字阅读大概需要5分钟。
内容图文
需求说明:
// 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") 10publicclass ServletDemo1 extends HttpServlet { 11 @Override 12publicvoid init() throws ServletException { 13 System.out.println("init()方法"); 14 } 1516protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 System.out.println("doPost()方法"); 18 doGet(request, response); 19 } 2021protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 22 String a = request.getParameter("a"); 23 String b = request.getParameter("b"); 24int 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 } 3637 @Override 38publicvoid 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. 重定向效果图:
原文:https://www.cnblogs.com/chris0710/p/8970543.html
内容总结
以上是互联网集市为您收集整理的idea创建简单web项目分析Servlet的请求转发与重定向的区别全部内容,希望文章能够帮你解决idea创建简单web项目分析Servlet的请求转发与重定向的区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。