Struts2实现简易计算器
/20170918_chr_calActionchr/src/nuc/sw/action/CalAction.java
package nuc.sw.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class CalAction extends ActionSupport {
private float num1;
private float num2;
private String op;
public float getNum1 () {
return num1;
}
public void setNum1 (float num1) {
this .num1 = num1;
}
public float getNum2 () {
return num2;
}
public void setNum2 (float num2) {
this .num2 = num2;
}
public String getOp () {
return op;
}
public void setOp (String op) {
this .op = op;
}
public String calculater (){
float result=0 ;
switch (op.charAt(0 )){
case '+' :result=num1+num2;break ;
case '-' :result=num1-num2;break ;
case '*' :result=num1*num2;break ;
case '/' :result=num1/num2;
}
ActionContext.getContext().put("result" , result);
return "calOK" ;
}
}
/20170918_chr_calActionchr/src/struts.xml
<struts >
<package name ="Cal" extends ="struts-default" namespace ="/" >
<action name ="CalAction" class ="nuc.sw.action.CalAction" method ="calculater" >
<result name ="calOK" >
/Cal.jsp
</result >
</action >
</package >
</struts >
/20170918_chr_calActionchr/WebContent/Cal.jsp
<%@ 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>Insert title here</title>
</head>
<body>
<form action="CalAction" method ="get" >
操作数1 :<input type ="text" name="num1" value ="${requestScope.num1}" ><br>
操作符号:<input type ="radio" name="op" value ="+" ${requestScope.op=="+" ?"checked" :"" }>+
<input type ="radio" name="op" value ="-" ${requestScope.op=="-" ?"checked" :"" }>-
<input type ="radio" name="op" value ="*" ${requestScope.op=="*" ?"checked" :"" }>*
<input type ="radio" name="op" value ="/" ${requestScope.op=="/" ?"checked" :"" }>/<br>
操作数2 :<input type ="text" name="num2" value =" ${requestScope.num2 }" ><br>
<input type ="submit" value ="计算" ><br>
结果: <input type ="text" value ="${requestScope.result} " >
</form>
</body>
</html>