1.设计Action类

Addaction.java

package com.action;

public class Addaction {
    private double x;
    private double y;
    private double sum;

    // 求值Action方法,并返回"-"或“+”
    public String CalculateSum() {
        String forward = null;
        sum = x+y;
        if (sum < 0) {
            forward = "-";
        } else {
            forward = "+";
        }
        return forward;
    }
    public Addaction() {//必带无参构造方法

    }
    public Addaction(double x,double y) { //带参数构造方法,但只有两个参数x、y
        this.x=x;
        this.y=y;
        this.sum=x+y;
    }
    //各属性的getter/setter方法
    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public double getY() {
        return y;
    }
    public void setY(double y) {
        this.y = y;
    }
    public double getSum() {
        return sum;
    }
    public void setSum(double sum) {
        this.sum = sum;
    }

}

2.设计JSP页面

input.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>两数之和计算</title>
</head>
<body>
<form action="opadd" method="post">
<table>
<tr>
<th colspan="2">请输入两个实数:</th>
</tr>
<tr>
<td align="right">加数:</td>
<td><input type="text" name="x" /></td> <%–保持和Action类的属性一致 –%>
</tr>
<tr>
<td align="right">被加数:</td>
<td><input type="text" name="y" /></td>
</tr>
<tr>
<td align="right"><input type="submit" value="求和" /></td>
</tr>
</table>
</form>
</body>
</html>

和为正数的页面

negative.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>计算结果为负数的页面</title>
</head>
<body>
代数和为负整数,其和值为:${x}+${y}=${sum}
</body>
</html>

和为负数的页面。

positive.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>计算结果为大于等于0的页面</title>
</head>
<body>
代数和为非负整数,其和值为:${x}+${y}=${sum}<br>
</body>
</html>

3.修改struts.xml文件

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="default" namespace="/" extends="struts-default">

<action name="opadd" class="com.action.Addaction" method="CalculateSum">
<result name="+">positive.jsp</result>
<result name="-">/negative.jsp</result>
</action>

</package>
</struts>

4.效果图