程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 簡易Servlet計算器,servlet計算器

簡易Servlet計算器,servlet計算器

編輯:JAVA綜合教程

簡易Servlet計算器,servlet計算器


編寫一個簡易的Servlet計算器,暫時僅能實現 + - * / % 五種運算

jsp界面:

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Servlet計算器</title> 8 </head> 9 <body> 10 <form action="TestJSQ" method="post"> 11 <input type="text" name="shu1"> 12 <input type="text" name="yunsuan" > 13 <input type="text" name="shu2"> 14 <input type="submit" value="="> 15 16 </form> 17 </body> 18 </html> View Code

Servlet程序:

1 package com.sp.web; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 public class Test_JSQ extends HttpServlet { 10 private static final long serialVersionUID = 1L; 11 12 public Test_JSQ() { 13 super(); 14 15 } 16 17 protected void doGet(HttpServletRequest request, HttpServletResponse response) 18 throws ServletException, IOException { 19 20 response.setCharacterEncoding("UTF-8"); 21 response.setContentType("text/html"); 22 Double num1 = Double.parseDouble(request.getParameter("shu1")); 23 Double num2 = Double.parseDouble(request.getParameter("shu2")); 24 String ysf = request.getParameter("yunsuan"); 25 26 Double jg = 0.0; 27 if (ysf.equals("+")) { 28 jg = num1 + num2; 29 response.getWriter().write(num1 + " + " + num2 + " = " + jg); 30 } else if (ysf.equals("-")) { 31 jg = num1 - num2; 32 response.getWriter().write(num1 + " - " + num2 + " = " + jg); 33 } else if (ysf.equals("*")) { 34 jg = num1 * num2; 35 response.getWriter().write(num1 + " × " + num2 + " = " + jg); 36 } else if (ysf.equals("/")) { 37 if (num2 != 0) { 38 jg = num1 / num2; 39 response.getWriter().write(num1 + " ÷ " + num2 + " = " + jg); 40 } else { 41 response.getWriter().write("除數不能為零"); 42 } 43 } else if (ysf.equals("%")) { 44 jg = num1 % num2; 45 response.getWriter().write(num1 + " % " + num2 + " = " + jg); 46 } 47 48 49 } 50 51 protected void doPost(HttpServletRequest request, HttpServletResponse response) 52 throws ServletException, IOException { 53 54 doGet(request, response); 55 } 56 57 } View Code

運行:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved