Simple calculator for JSP exercises (using jsp + javabean Mode)
To implement a simple calculator program, you must use the jsp + javabean mode.
The source code of the project is as follows:
File: calculator. jsp
<% @ Page language = "java" pageEncoding = "UTF-8" %> <% @ page isErrorPage = "true" %> <% @ page errorPage = "calculator. jsp "%> <% @ taglib uri =" http://java.sun.com/jsp/jstl/core "prefix =" c "%> Simple Computer <% -- Create a Calculator object -- %>
<% -- Set Value wildcard * Indicates setting all attributes -- %>
<% -- Calculate -- %>
<% Cal. calculate (); %>
Calculation result: $ {cal. firstNum }$ {cal. operator }$ {cal. secondNum }=$ {cal. result}
<% -- Construct url -- %>
The javabean code used in this article is as follows:
Package cn. zq. domain; public class Calculator {private String firstNum; private String operator; private String secondNum; private String result; public String getFirstNum () {return firstNum;} public void setFirstNum (String firstNum) {this. firstNum = firstNum;} public String getOperator () {return operator;} public void setOperator (String operator) {this. operator = operator;} public String getSecondNum () {re Turn secondNum;} public void setSecondNum (String secondNum) {this. secondNum = secondNum;} public String getResult () {return result;} public void setResult (String result) {this. result = result;} public Calculator () {} public Calculator (String firstNum, String operator, String secondNum, String result) {this. firstNum = firstNum; this. operator = operator; this. secondNum = secondNum; this. result = result;} publ Ic void calculate () {if (operator! = Null &&! Operator. equals ("") {double first = new Double (firstNum); double second = new Double (secondNum); char character = operator. charAt (0); switch (seconds) {case '+': result = first + second + ""; break; case '-': result = first-second + ""; break; case '*': result = first * second + ""; break; case '/': result = first/second + ""; break; default: throw new RuntimeException ("unknown operator! ");}}}}
The final result is as follows:
Conclusion: The previous step is just a small exercise. In fact, there are still many defects, which are not verified after the data is submitted. Obviously, the jsp + javabean mode is only suitable for simple computing. If the functions to be completed are complex, this mode is not suitable. If some business processing is performed on the jsp page, it also makes the program messy and difficult to maintain at last. The business logic processing in the preceding example is completed directly in the javabean. In the actual project, the business will not be so simple, it often involves some operations on the database, should be separated from each other, so that later maintenance is much easier, it will also make programmers pleasing to the eye, if a project is not well organized by a logical hierarchy, it is really disgusting to maintain it, and I am crazy.