这个表单也是写在servlet中吗?不是太懂这个思路。
package per.rr.servlet.direct; 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 SumServlet */ @WebServlet("/direct/sum") public class SumServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SumServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("请输入100以内的数字", "5"); int n = 0; int sum = 0; for(int i = 0; i <= n; i++){ sum = sum + i; } String output = "<h1>求累加和</h1>"; response.setContentType("text/html;charset=utf-8"); response.getWriter().println(output); request.getRequestDispatcher("/direct/show").forward(request, response); } }
0
收起
正在回答 回答被采纳积分+1
2回答
慕娘56302749
2018-12-28 18:23:12
你可以参考一下这个代码:
public class Add extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置格式 req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write("<html>"); resp.getWriter().write("<head>"); resp.getWriter().write("<body>"); resp.getWriter().write("<form action='number' >"); resp.getWriter() .write("<input type='text' name='number' placeholder='请输入100以内的数字' value=''/><br/>"); resp.getWriter().write("<input type='submit' value='求累加和'/>"); resp.getWriter().write("</form>"); resp.getWriter().write("</body>"); resp.getWriter().write("</head>"); resp.getWriter().write("</html>"); req.getRequestDispatcher("/Add/number").forward(req, resp); } }
public class number extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置格式 req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); // 获得请求数据 String num = req.getParameter("number"); // 处理数据 int sum = 0; char[] ch = num.toCharArray(); for (int i = 0; i < ch.length; i++) { if (ch[i] == ' ') { } else { sum = (ch[i] - '0') + sum; } } // 得到响应 resp.getWriter().write("累加和是:" + sum); } }
Java Web基础入门2018版
- 参与学习 716 人
- 提交作业 185 份
- 解答问题 1363 个
会Java?懂前端基础?想学后台开发?那么,赶快来学习《Java Web入门》路径吧。本路径主要介绍Java Web的基础知识,并配有大量案例,定会让你收获多多!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星