一、控制台实现乘法表
package com.shanrengo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MultiTableServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + "*" + i + "=" + j*i + "\t"); } System.out.println(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
二、输出浏览器代码修改
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { out.print(j + "*" + i + "=" + j*i + "\t"); } out.println(); } }
三、让用户提交一个数字
1.新建一个用户页面input.html
<form action="MultiTableServlet" method="post"> 请输入一个数字:<input type="text" name="number"/> <input type="submit" value="打印"/> </form>
action可填写相对路劲,也可以填写绝对路径
相对路径:将URL最后地址换成相对地址,例如action填写MultiTableServlet就可以了。
如果input.html页面和MultiTableServlet不是同一个目录的,则会出现404错误,如果是在上一个目录就要再action填写../MultiTableServlet
绝对路径:action填写,/testServlet/MutiTableServlet或者http://localhost:8080/testServlet/MutiTableServlet
2.修改Servlet
package com.shanrengo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MultiTableServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String numberStr = request.getParameter("number"); int number = 0; try { number = Integer.parseInt(numberStr); } catch (NumberFormatException e) { // TODO Auto-generated catch block //e.printStackTrace(); throw new RuntimeException("不是数字"); } PrintWriter out = response.getWriter(); for (int i = 1; i <= number; i++) { for (int j = 1; j <= i; j++) { out.print(j + "*" + i + "=" + j*i + "\t"); } out.println(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
项目附件:http://pan.baidu.com/s/1pJugL31
注:我是初学者,发表博客只是学习笔记,欢迎探讨指教,希望可以结实良师益友。
Servlet乘法表学习笔记
时间: 2024-09-30 19:45:49