MVC实现简单的四则运算

MVC实现简单的四则运算

1.jsp

<body>
    <form action="frame_study/ArithmetiServlet" method="post">
    <table><tr>
    <td><input type="text" name="input1" value="${requestScope.ac.num1}"/></td>
    <td>
    <select name="operate">
    <option value="">${requestScope.ac.operate}</option>
    <option value="+">+</option>
     <option value="-">-</option>
      <option value="*">*</option>
       <option value="/">/</option>
    </select>
    </td>
     <td><input type="text" name="input2" value="${requestScope.ac.num2}"/></td>
     <td><input type="submit" name="out" value="=" /></td>
      <td><input type="text" name="outcome" value="${requestScope.ac.result}"/></td>
    </tr></table>
    </form>
  </body>

2.servlet

Arithmetic ac=new Arithmetic();
		//从jsp页面拿值
		double num1=Double.parseDouble(request.getParameter("input1"));
		double num2=Double.parseDouble(request.getParameter("input2"));
		double result = 0;
		String operate=request.getParameter("operate");
		//判断执行的操作
		if("+".equals(operate)){
		result=Arithmetic.add(num1,num2);
		}
		else if("-".equals(operate)){
			result=Arithmetic.sub(num1, num2);
		}
		else if("*".equals(operate)){
			result=Arithmetic.mul(num1, num2);
		}
		else if("/".equals(operate)){
			result=Arithmetic.div(num1, num2);
		}
		ac.setNum1(num1);
		ac.setNum2(num2);
		ac.setResult(result);
		ac.setOperate(operate);
		//将arithmetic独享封装
		request.setAttribute("ac", ac);
		request.getRequestDispatcher("../frame_chap01/Arithmetic.jsp").forward(request, response);
		out.flush();
		out.close();

3.javabean


public class Arithmetic {
	private double num1;
	private double num2;
	private double result;
	private String operate;
	
	public double getNum1() {
		return num1;
	}
	public void setNum1(double num1) {
		this.num1 = num1;
	}
	public double getNum2() {
		return num2;
	}
	public void setNum2(double num2) {
		this.num2 = num2;
	}
	public double getResult() {
		return result;
	}
	public void setResult(double result) {
		this.result = result;
	}
	public String getOperate() {
		return operate;
	}
	public void setOperate(String operate) {
		this.operate = operate;
	}
	//加法
	public static double add(double num1,double num2){
		return num1+num2;
		
	}
	//减法
	public static double sub(double num1,double num2){
		return num1-num2;
	}
	//乘法
	public static double mul(double num1,double num2){
		return num1*num2;
	}
	//除法
	public static double div(double num1,double num2){
		DecimalFormat dec=new DecimalFormat("0.00");
		String re=dec.format(num1/num2);
		return Double.parseDouble(re);
	}

你可能感兴趣的:(web前段,web,jsp,mvc)