页面: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script type="text/javascript" src="js/jquery.js"> </script> <script> $(document).ready( function() { //1 按钮关联事件 $("#btn").click( function () { //构造ajax参数 var paras = "a="+$("#a").val()+"&b=" +$("#b").val()+"&op="+$("#op").val(); //发起ajax请求 $.ajax( { type:"get", url:"CalculatorServlet", data:paras, dataType:"json", cache:false, success:function(c) { var info = ""; //使用增强for,遍历json对象的所有属性 if(c.a!=undefined) { alert(c.a+c.show_op+c.b+"="+c.result) } else { alert("错误编号:"+c.errcode+",错误信息:"+c.errmsg); } } } ); } ); } ); </script> <body> 请输入a值:<input id="a" value="1"/> <select id="op"> <option value="add">+</option> <option value="sub">-</option> <option value="multi">*</option> <option value="div">/</option> </select> 请输入b值:<input id="b" value="2"/> <input id="btn" type="button" value="获得结果"/> </body> </html>
控制器: 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; import com.google.gson.Gson; public class CalculatorServlet extends HttpServlet { /** * Constructor of the object. */ public CalculatorServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1 中文处理 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); Gson gson = new Gson(); //2 读取入参 int a = -1; int b = -1; try { a = Integer.parseInt(request.getParameter("a")); b = Integer.parseInt(request.getParameter("b")); } catch (Exception e) { //创建1个错误消息对象,用json写回。方法提前终止。 Msg m = new Msg(1, "输入的数字格式有误!"); String json = gson.toJson(m); response.getWriter().print(json); response.getWriter().flush(); response.getWriter().close(); return; } String op = request.getParameter("op"); //3 创建calculator对象 Calculator c = new Calculator(a, b, op); c.cal();//执行计算,算出结果 //4 转成json字符串返回 String json = gson.toJson(c); response.getWriter().print(json); response.getWriter().flush(); response.getWriter().close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
//用于提示错误信息的类 public class Msg { private int errcode; private String errmsg; public int getErrcode() { return errcode; } public void setErrcode(int errcode) { this.errcode = errcode; } public Msg(int errcode, String errMsg) { super(); this.errcode = errcode; errmsg = errMsg; } }
public class Calculator { private int a; private String op; private int b; private String show_op; private int result; public Calculator(int a, int b, String op) { super(); this.a = a; this.b = b; this.op = op; } public String getOp() { return op; } public void setOp(String op) { this.op = op; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } //执行计算,算出result public void cal() { if("add".equals(op)) { result = a+b; show_op = "+"; } else if("sub".equals(op)) { result = a-b; show_op = "-"; } else if("multi".equals(op)) { result = a*b; show_op = "*"; } else if("div".equals(op)) { result = a/b; show_op = "/"; } } }