首页 > 代码库 > Servlet乘法表学习笔记
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 { 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="http://www.mamicode.com/打印"/> </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
注:我是初学者,发表博客只是学习笔记,欢迎探讨指教,希望可以结实良师益友。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。