本文主要是介绍Jsp和Servlet分工之求a+b的和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
流程:
在WebContent文件下面建立sum文件夹,再在这里面新建form.jsp和result.jsp页面,在
form.jsp:
<body>
<span style="white-space:pre"> </span>//是项目名加资源路径<form action="/Web/SumServlet" method="post">整数a:<input type="text" name="a" /> <br />整数b:<input type="text" name="b" /> <br /><input type="submit" value="提交" /></form>
</body>
SumServlet:
package sum;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@WebServlet("/SumServlet")
public class SumServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// String a2 = request.getParameter("a");//整形有自动装箱拆箱机制 获取参数a bint a = Integer.parseInt(request.getParameter("a"));int b = Integer.parseInt(request.getParameter("b"));int sum = a + b;request.setAttribute("sum", sum);request.getRequestDispatcher("/sum/result.jsp").forward(request, response);}}
result.jsp:
<body><% //应该是获取的属性getAttribute("sum")而非getParameter("sum"),在Servlet里面存储的就是setAttribute("sum",sum)Integer sum2 = (Integer)request.getAttribute("sum");//int sum = Integer.parseInt(request.getParameter("sum"));//错误的,获取参数应该是用户提交的表单%><%=sum2 %>
</body>
这篇关于Jsp和Servlet分工之求a+b的和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!