Servlet实现计算器
package com.hanqi.web; 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; /** * Servlet implementation class HWjisuan */ public class HWjisuan extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HWjisuan() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); String f=request.getParameter("f"); String a=request.getParameter("a"); String b=request.getParameter("b"); double aa=Double.parseDouble(a); double bb=Double.parseDouble(b); if(a!=""&&b!="") { if(f.equals("/")&&bb!=0) { pw.println(aa/bb); } else { pw.println("除数不能为0"); } }else { pw.println("不能为空"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>计算器</title> </head> <body> <form action="jisuan" method="post"> <table> <tr> <td><input type="text" name="a" style="font-size: 15px; width: 50px;"/></td> <td><input type="text" name="f" style="font-size: 15px; width: 15px;"/></td> <td><input type="text" name="b" style="font-size: 15px; width: 50px;"/></td> <td><input type="submit" value="等于"/></td> </tr> </table> </form> </body> </html>
运行结果:
时间: 2024-10-13 16:15:57