1.创建Maven导入jia包
2.写web.xml
<web-app></web-app>中加入
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.编写JSP
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML >
<html>
<head>
<title>简单的计算器</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">
</head>
<body>
<s:form action="jisuan">
<s:label value="简单计算器"></s:label>
<s:textfield name="num1" label="第一个数"></s:textfield>
<s:select name="check" list="{'+','-','*','/'}" label="运算符"></s:select>
<s:textfield name="num2" label="第二个数"></s:textfield>
<s:submit value="计算"></s:submit>
</s:form>
</body>
</html>
4.编写Aciton
package com.szxs.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
public class DealAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 761775720829200479L;
private String num1; //第一个操作数
private String num2; //第二个操作数
private String check; //运算符
public double num3; //计算结果
public String getNum1() {
return num1;
}
public void setNum1(String num1) {
this.num1 = num1;
}
public String getNum2() {
return num2;
}
public void setNum2(String num2) {
this.num2 = num2;
}
public String getCheck() {
return check;
}
public void setCheck(String check) {
this.check = check;
}
public double getNum3() {
return num3;
}
public void setNum3(double num3) {
this.num3 = num3;
}
public String execute(){
String x=getNum1(); //获取第一个数
String y=getNum2(); //获取第二个数
double num4=Double.parseDouble(x); //将第一个数转换为double型
double num5=Double.parseDouble(y); //将第二个数转换为double型
System.out.println(num4);
if(check.equals("+")){ //进行加法运算
num3=num4+num5;
}
if(check.equals("-")){ //进行减法运算
num3=num4-num5;
}
if(check.equals("*")){ //进行乘法运算
num3=num4*num5;
}
if(check.equals("/")){ //进行除法运算
num3=num4/num5;
}
ActionContext.getContext().getSession().put("num3", num3); //将计算结果保存到session中
return SUCCESS;
}
5.编写Struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="first" extends="struts-default"><!-- 定义一个package -->
<!-- 对action返回结果的配置 -->
<action name="jisuan" class="com.mr.action.DealAction">
<result name="success">/result.jsp</result>
<result name="login">/index.jsp</result>
</action>
</package>
</struts>
6.部署和测试