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 b
		int 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>


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。