加法计算器(转发和重定向)
运行显示:
转发
重定向
代码:
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); } }