1.设计Action类
Addaction.java
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
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
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<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
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计算结果为负数的页面</title>
</head>
<body>
代数和为负整数,其和值为:${x}+${y}=${sum}
</body>
</html>
和为负数的页面。
positive.jsp
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<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
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
<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.效果图

评论