简易Servlet计算器1.0
编写一个简易的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" style="font-size: 12px; width: 12px;"> 13 <input type="text" name="shu2"> 14 <input type="submit" value="="> 15 16 </form> 17 </body> 18 </html>
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 }
运行: