AServlet.java
package com.ywq; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从form.jsp页面获取参数 String num1=request.getParameter("num1"); String num2=request.getParameter("num2"); //参数类型转换 int a=Integer.parseInt(num1); int b=Integer.parseInt(num2); int sum=a+b; //将运算结果保存在request域中 request.setAttribute("result", sum); //请求转发,使转换到显示结果页面。 RequestDispatcher rd=request.getRequestDispatcher("/add/result.jsp"); rd.forward(request, response); } }
form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>这个页面用来输入两个参数</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="/day11_1/AServlet" method="post"> 加数1:<input type="text" name="num1"/><br> 加数2:<input type="text" name="num2"/><br> <input type="submit" value="运算"> </form> </body> </html>
result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>运算结果显示页面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% Integer sum=(Integer)request.getAttribute("result"); %> <%=sum %> </body> </html>
项目工程截图如下:
来源: https://www.cnblogs.com/lanzhi/p/6467289.html