有没有按照本节课的思想进行编程?
InputNum.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://localhost:8888/Servlet_advanced/test2_6/do" method="get"> <input type="text" name="num" placeholder="请输入100以内的数字"> <input type="submit" value="求累加和"> </form> </body> </html>
DoServlet.java
package com.imooc.servlet.test2_6; 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; /** * Servlet implementation class DoServlet */ @WebServlet("/test2_6/do") public class DoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DoServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String str = request.getParameter("num"); int num = Integer.parseInt(str); int sum = 0; for(int i = 0; i <= num; i++) { sum+= i; } request.setAttribute("num",num); request.setAttribute("result",sum); request.getRequestDispatcher("/test2_6/show").forward(request, response); } }
ShowResult.java
package com.imooc.servlet.test2_6; 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; /** * Servlet implementation class InputNum */ @WebServlet("/test2_6/show") public class ShowResult extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ShowResult() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=utf-8"); int num = (int)request.getAttribute("num"); int result = (int)request.getAttribute("result"); response.getWriter().println("0到"+num+"的累加和为:"+result); } }
8
收起
正在回答 回答被采纳积分+1
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10205 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星