Java项目案例之---加法计算器(转发和重定向)
2024-10-07 11:17:55
加法计算器(转发和重定向)
运行显示:
转发
重定向
代码:
index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/7/22 0022
Time: 下午 5:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="CountServlet" method="post">
<h3>加法计算器</h3>
加数1:<input type="number" name="one">
加数2:<input type="number" name="two">
<input type="submit" value="计算">
</form>
</body>
</html>
count.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/7/22 0022 Time: 下午 5:51 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 计算结果:<%=request.getAttribute("count")%> <!--计算结果:<%=application.getAttribute("count")%>--> </body> </html>
package servlet; 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("/CountServlet") public class CountServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String one=request.getParameter("one"); int o=Integer.parseInt(one);//强制转换,将String类型的数据转换成int类型 String two=request.getParameter("two"); int t=Integer.parseInt(two);//强制转换,将String类型的数据转换成int类型 System.out.println(one+" "+two); int c=o+t; String co=String.valueOf(c);//将int类型的数据转换成String类型 //转发,可以携带数据 request.setAttribute("count",co); request.getRequestDispatcher("count.jsp").forward(request,response); //用于存放数据 // ServletContext s=this.getServletContext(); // s.setAttribute("count",co); //重定向只能依靠ServletContext获取数据 // response.sendRedirect("count.jsp"); System.out.println(co); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
最新文章
- 入门:Java Map<;String,String>;遍历及修改
- android nagative drawer图标跟标题适配
- MVC项目创建与项目结构介绍
- Web Server 使用WebClient 发送https请求 The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
- IP地址转换成Long型数字的算法
- CloudStack 4.2 与CloudStack 4.1二级存储API发生变化
- Flex:CSS3布局利器
- 知识网之C++总结
- JavaScript之惰性函数
- ORM对象关系映射之使用GreenDAO进行CRUD操作
- rsync的详细配置
- [Swift]LeetCode875. 爱吃香蕉的珂珂 | Koko Eating Bananas
- Quartz的JobDetail没有触发器指向时会被删除的问题
- P2761 软件补丁问题
- 深度学习课程笔记(十三)深度强化学习 --- 策略梯度方法(Policy Gradient Methods)
- Tween animation
- MyEclipse *的安装步骤和破解(32位和64位皆适用)(图文详解)
- 【Python】详解Python多线程Selenium跨浏览器测试
- 【Leetcode】86. Partition List
- 百度编辑器UEditor不能插入音频视频的解决方法